intmain() { int i, j, is_prime; for (i = LEFT; i <= RIGHT; i++) { is_prime = 1; for (j = 2; j * j <= i; j++) { if (i % j == 0) { is_prime = 0; break; } } if (is_prime) { printf("%d is a prime number.\n", i); } }
// options // WNOHANG: return immediately if no child has exited. // pid // > 0: wait for the child whose process ID is equal to the value of pid. // = 0: meaning wait for any child process whose process group ID is equal to that of the calling process at the time of the call to waitpid(). // -1: meaning wait for any child process. // <-1: meaning wait for any child process whose process group ID is equal to the absolute value of pid. pid_twaitpid(pid_t pid, int *wstatus, int options);
intwaitid(idtype_t idtype, id_t id, siginfo_t *infop, int options);
// returns true if the child terminated normally WIFEXITED(wstatus)
// returns the exit status of the child. // This macro should be employed only if WIFEXITED returned true. WEXITSTATUS(wstatus)
// returns true if the child process was terminated by a signal. WIFSIGNALED(wstatus)
// returns the number of the signal that caused the child process to terminate. // This macro should be employed only if WIFSIGNALED returned true. WTERMSIG(wstatus)
intmain() { int i, j, is_prime; pid_t pid; for (i = LEFT; i <= RIGHT; i++) { pid = fork(); if (pid < 0) { perror("fork()"); exit(1); } elseif (pid == 0) { // Child process is_prime = 1; for (j = 2; j * j <= i; j++) { if (i % j == 0) { is_prime = 0; break; } } if (is_prime) { printf("%d is a prime number.\n", i); } // Child process exits after checking exit(0); } } for (i = LEFT; i <= RIGHT; i++) { wait(NULL); } exit(0); }
#define LEFT 30000000 #define RIGHT 30000200 #define N 3
intmain() { int i, j, n, is_prime; pid_t pid;
for (n = 0; n < N; n++) { pid = fork(); if (pid < 0) { perror("fork()"); exit(1); } if (pid == 0) { // Child process for (i = LEFT + n; i <= RIGHT; i += N) { is_prime = 1; for (j = 2; j * j <= i; j++) { if (i % j == 0) { is_prime = 0; break; } } if (is_prime) { printf("[%d] %d is a prime number.\n", n, i); } } // Child process exits after checking exit(0); } } for (i = 0; i <= N; i++) { wait(NULL); } exit(0); }
4. exec 函数族
为什么 bash 创建的子进程是 hello ?
1 2 3 4 5 6 7 8 9
$ ps axf 16066 ? S 0:00 | \_ /init 16068 pts/6 Ss+ 0:00 | \_ -bash 17451 pts/6 S 0:00 | \_ ./src/hello 17452 pts/6 S 0:00 | \_ ./src/hello 17453 pts/6 S 0:00 | \_ ./src/hello 17454 pts/6 S 0:00 | \_ ./src/hello 17455 pts/6 S 0:00 | \_ ./src/hello ...
API
执行一个文件
The exec() family of functions replaces the current process image with a new process image.