1.多进程并发

来源:互联网 发布:卖肉漫画软件 编辑:程序博客网 时间:2024/06/06 13:22

题目:编写程序,利用fork()产生来两个进程,首先显示一下两个子进程及父进程的进程标识符,然后,让父进程显示1-26个数字,子进程1显示26个大写字母,子进程2显示26个小写字母。让大小写字母及数字夹杂交错输出。

#include<stdio.h>#include<string.h>#include<unistd.h>int main(){int p1, p2;int i = 1;char ch1 = 'A', ch2 = 'a';while((p1 = fork()) == -1);if(p1){while((p2 = fork()) == -1);if(p2){//parent;printf("This is parent process, pid = %d\n", getpid());while(i <= 26){printf("Parent process print : %d\n", i);i = i + 1;sleep(1);}}else{//child2printf("This is child process2, pid = %d\n", getpid());while(ch2 <= 'z'){printf("Child process2 print : %c\n", ch2);ch2 = ch2 + 1;sleep(1);}}}//ifelse{//child1printf("This is child process1, pid = %d\n", getpid());while(ch1 <= 'Z'){printf("Child process1 print : %c\n", ch1);ch1 = ch1 + 1;sleep(1);}}//elsereturn 0;}

修改程序,让两个子进程夹杂输出结束后,父进程输出开始。

#include<stdio.h>#include<string.h>#include<unistd.h>int main(){int p1, p2;int i = 1;char ch1 = 'A', ch2 = 'a';while((p1 = fork()) == -1);if(p1){while((p2 = fork()) == -1);if(p2){//parent;printf("This is parent process, pid = %d\n", getpid());wait(0);//修改wait(0);//修改while(i <= 26){printf("Parent process print : %d\n", i);i = i + 1;sleep(1);}}else{//child2printf("This is child process2, pid = %d\n", getpid());while(ch2 <= 'z'){printf("Child process2 print : %c\n", ch2);ch2 = ch2 + 1;sleep(1);}}}//ifelse{//child1printf("This is child process1, pid = %d\n", getpid());while(ch1 <= 'Z'){printf("Child process1 print : %c\n", ch1);ch1 = ch1 + 1;sleep(1);}}//elsereturn 0;}


0 0
原创粉丝点击