如何更改程序以使功能function_delayed_1
和function_delayed_2
仅同时执行一次:
int main(int argc, char *argv[]) {
printf("message 1.\n");
fork();
function_delayed_1();
function_delayed_2();
printf("message 2.\n");
}
阅读man
fork的页面,并google一些示例fork();
,您的代码应如下所示:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
pid_t pid; // process ID
printf("message 1.\n");
pid = fork();
if (pid < 0) {
perror("fork");
return;
}
if (pid == 0) {
function_delayed_1(); // child process
}
else {
function_delayed_2(); // parent process
}
printf("message 2.\n");
}
int main(int argc, char *argv[]) {
printf("message 1.\n"); // printed once by parent process
if(fork())
function_delayed_1(); // executed by parent process
else
function_delayed_2(); // executed by child process
printf("message 2.\n"); // will be printed twice once by parent & once by child.
}