看来我只能是搬搬大佬的文章,自己贴下没营养的代码了。。。
task1
#include <stdio.h>
#include <unistd.h>
//#define character
#define sentence
int main(){
int pid1, pid2;
while((pid1 = fork()) == -1);//创建第一子进程
// fork调用的一个奇妙之处就是它仅仅被调用一次,却能够返回两次
// 1)在父进程中,fork返回新创建子进程的进程ID;
// 2)在子进程中,fork返回0;
// 3)如果出现错误,fork返回一个负值;
//
// fork是把进程当前的情况拷贝一份
// 执行fork时,进程已经执行完了一段代码
// fork只拷贝下一个要执行的代码到新的进程。
if(pid1 == 0) // 第一子进程输出字符b
#if defined character
printf("b");
#elif defined sentence
printf("This is the first subprocess.\n");
#endif
else{
while((pid2 = fork()) == -1);//创建第二子进程
if(pid2 == 0){ //第二子进程输出字符c
#if defined character
printf("c");
#elif defined sentence
printf("This is the second subprocess.\n");
#endif
}
else //父进程中输出字符a
#if defined character
printf("a");
#elif defined sentence
printf("This is the parent process.\n");
#endif
}
// 这就跟printf的缓冲机制有关了
// printf某些内容时,操作系统仅仅是把该内容放到了stdout的缓冲队列里了,并没有实际的写到屏幕上。
// 但是,只要看到有\n 则会立即刷新stdout,因此就马上能够打印了。
}
task2
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <wait.h>
#include <time.h>
#define ALARM
int wait_flag;
void waiting(){
while(wait