问题描述:
编写一段程序测试图10-24中父进程和子进程的同步数,要求进程创建一个文件并向文件中写一个整数0,然后,进程调用fork,接着,父进程和子进程交替增加文件中的计数器值,每次计数器值增加1时,打印是哪一个进程(子进程或父进程)进行了该增加1操作。
解答:
#include"apue.h"
#include<fcntl.h>
#define RWRW (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) //文件权限为用户读写组读写
const char *dscrpt_child = "output after child process, value: "; //打印是子进程进行了操作
const char *dscrpt_parent = "output after parent process, value: "; //打印时父进程进行了操作
int main(void)
{
pid_t pid;
int fd, count = 0, i, j;
char *initial_str = "the initial num: 0\n";
char str_count[10];
TELL_WAIT();
fd = open("testfile.txt", O_RDWR | O_CREAT | O_TRUNC | O_APPEND, RWRW);//新建一个名为“testfile.txt”的文本文件
if (write(fd, initial_str, strlen(initial_str)) < strlen(initial_str)) //写入第一行,初始值为0
err_sys("write error\n");
if ((pid = fork()) < 0)
err_sys("fork error\n");
else if (pid == 0){ //子进程
TELL_PARENT(getppid()); //给父进程发送信号,父进程先走
for (i = 0; i < 10; i++ ) //只尝试10次加1操作
{
WAIT_PARENT(); //等待来自父进程的信号
count = 2 * ( i + 1 );
if(write(fd, dscrpt_child, strlen(dscrpt_child)) < strlen(dscrpt_child))//写入子进程操作描述
err_sys("write error\n");
if(sprintf(str_count, "%d\n", count) < 0) //把count转换成字符串
err_sys("sprintf error\n");
if(write(fd, str_count, strlen(str_count)) < strlen(str_count))//在子进程操作描述后追加数字和换行符
err_sys("write error\n");
TELL_PARENT(getppid());//给父进程发信号
}
exit(0);
}
else //父进程
{
for (j = 0; j < 10; j++)
{
WAIT_CHILD(); //等待来自子进程的信号
count = 2 * j + 1;
if(write(fd, dscrpt_parent, strlen(dscrpt_parent)) < strlen(dscrpt_paren t))
err_sys("write error\n");
if(sprintf(str_count, "%d\n", count) < 0)
err_sys("sprintf error\n");
if(write(fd, str_count, strlen(str_count)) < strlen(str_count)) err_sys("write error\n");
TELL_CHILD(pid); //给子进程发信号
}
}
close(fd);
printf("All processes done!\n");
exit(0);
}