The Android Open Source Project | e16cb84 | 2009-03-03 19:32:58 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2008 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | * |
| 16 | * Simple cpu eater busy loop. Runs as a daemon. prints the child PID to |
| 17 | * std so you can easily kill it later. |
| 18 | */ |
| 19 | |
| 20 | #include <stdio.h> |
| 21 | #include <unistd.h> |
| 22 | #include <stdlib.h> |
| 23 | #include <fcntl.h> |
| 24 | #include <sys/types.h> |
| 25 | #include <sys/stat.h> |
| 26 | |
| 27 | |
| 28 | int main(int argc, char *argv[]) |
| 29 | { |
| 30 | pid_t pid; |
| 31 | int life_universe_and_everything; |
| 32 | int fd; |
| 33 | |
| 34 | switch(fork()) { |
| 35 | case -1: |
| 36 | perror(argv[0]); |
| 37 | exit(1); |
| 38 | break; |
| 39 | case 0: /* child */ |
| 40 | chdir("/"); |
| 41 | umask(0); |
| 42 | setpgrp(); |
| 43 | setsid(); |
| 44 | /* fork again to fully detach from controlling terminal. */ |
| 45 | switch(pid = fork()) { |
| 46 | case -1: |
| 47 | break; |
| 48 | case 0: /* second child */ |
| 49 | /* redirect to /dev/null */ |
| 50 | close(0); |
| 51 | open("/dev/null", 0); |
| 52 | close(1); |
| 53 | if(open("/dev/null", O_WRONLY) < 0) { |
| 54 | perror("/dev/null"); |
| 55 | exit(1); |
| 56 | } |
| 57 | fflush(stdout); |
| 58 | close(2); |
| 59 | dup(1); |
| 60 | for (fd = 3; fd < 256; fd++) { |
| 61 | close(fd); |
| 62 | } |
| 63 | /* busy looper */ |
| 64 | while (1) { |
| 65 | life_universe_and_everything = 42 * 2; |
| 66 | } |
| 67 | default: |
| 68 | /* so caller can easily kill it later. */ |
| 69 | printf("%d\n", pid); |
| 70 | exit(0); |
| 71 | break; |
| 72 | } |
| 73 | break; |
| 74 | default: |
| 75 | exit(0); |
| 76 | break; |
| 77 | } |
| 78 | return 0; |
| 79 | } |
| 80 | |
| 81 | |
| 82 | /* vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab */ |
| 83 | |