- 论坛徽章:
- 0
|
请问C语言中如何实现两个语句并发执行?
谢谢大家!
我查询了一下多进程编程,但我的程序比较简单,各进程相互独立,不需要相互通信,只使用了简单的fork()语句,我把代码贴出来以便有和我同样问题的参考!也希望高手能帮助看看如何可以优化!
- #include <stdio.h>;
- #include <unistd.h>;
- #include <sys/types.h>;
- #include <sys/wait.h>;
- void func1();
- void func2();
- void func3();
- int main(){
- pid_t pid1, pid2, pid3;
- pid1 = fork();
- if(pid1 == 0){
- printf("Hello from the child process!\n");
- printf("The child is exiting now!\n");
- func1();
- }
- else if( pid1 != -1 ){
- printf("Hello from the parent,pid %d.\n",getpid());
- printf("The parent has forked process %d.\n",pid1);
- pid2 = fork();
- if( pid2 == 0 ) func2();
- else if( pid2 != -1 ){
- printf("The parent has forked process %d.\n",pid2);
- pid3 = fork();
- if( pid3 ==0 ) func3();
- else if(pid3 != -1){
- printf("The parent has forked process %d.\n",pid3);
- waitpid(-1, NULL, 0);
- printf("The parent is exiting now.\n");
- }
- else{
- printf("There was an error with forking pid3!\n");
- }
- }
- else{
- printf("There was an error with forking pid2!\n");
- }
- }
- else{
- printf("There was an error with forking pid1!\n");
- }
- }
- void func1(){
- printf("I'm func1.\n");
- sleep(15);
- }
- void func2(){
- printf("I'm func2.\n");
- sleep(15);
- }
- void func3(){
- printf("I'm func3.\n");
- sleep(15);
- }
复制代码 |
|