"进程管理与通信实验1:进程创建与字符显示"

0 下载量 178 浏览量 更新于2024-04-10 收藏 1.16MB DOC 举报
#include <stdio.h> #include <unistd.h> int main(){ pid_t pid1, pid2; pid1 = fork(); if(pid1 < 0){ // fork failed printf("Fork failed\n"); } else if(pid1 == 0){ // child process 1 printf("Child Process 1: b\n"); } else{ // parent process pid2 = fork(); if(pid2 < 0){ // fork failed printf("Fork failed\n"); } else if(pid2 == 0){ // child process 2 printf("Child Process 2: c\n"); } else{ // parent process printf("Parent Process: a\n"); } } return 0; } 2. 修改程序,每个进程循环显示一句话: #include <stdio.h> #include <unistd.h> int main(){ pid_t pid1, pid2; pid1 = fork(); if(pid1 < 0){ // fork failed printf("Fork failed\n"); } else if(pid1 == 0){ // child process 1 while(1){ printf("Daughter Process: ...\n"); } } else{ // parent process pid2 = fork(); if(pid2 < 0){ // fork failed printf("Fork failed\n"); } else if(pid2 == 0){ // child process 2 while(1){ printf("Son Process: ...\n"); } } else{ // parent process while(1){ printf("Parent Process: ...\n"); } } } return 0; }