APUE习题10.6(父子进程同步)

本文通过一个具体的编程实例展示了如何在父子进程中实现同步操作,重点介绍了如何通过修改全局变量并在父子进程间传递信息来确保计数器的正确递增。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


编写一段程序测试图10_24中父子进程的同步函数,要求进程创建一个文件并向文件写一个整数0,然后进程调用fork,接着父子进程交替增加文件中的计数器值,每次计数器值增加1,打印是哪一个进程进行来该增加1操作


没有完全按照题目要求做,直接fork之后01234这样打印的

先上一个标准输出的实现


1、写到标准输出的实现

main.c:以下实现是有问题的

问题在于:子进程的数据空间、堆栈空间都会从父进程得到一个拷贝,而不是共享。在子进程对count进行++操作,并没有影响到父进程着哦您能够的count值,即使是全局变量也不会改变,《APUE》8.3节说到,子进程是父进程的副本(子进程获得父进程数据空间、堆和栈的副本)。父进程和子进程并不共享这些存储空间部分,父进程和子进程共享正文段。

#include "apue.h"

static int count = 0;
int main(void)
{
        pid_t pid;
        TELL_WAIT();


        
        if((pid = fork()) < 0 ){
                err_sys("fork error");
        } else if (pid == 0) {
                while(1){
                        TELL_WAIT();
                        WAIT_PARENT();
                        printf("output from child:");
                        printf("count=%d \n",count++);
                        TELL_PARENT(getppid());
                }
                exit(0);
        }
        else{
            printf("Output from parent:");
            printf("count=%d\n",count++);
            TELL_CHILD(pid);
            while(1){
                 sleep(2);
                 TELL_WAIT();
                 WAIT_CHILD();
                 printf("output from parent:");
                 printf("count=%d\n",count++);
                 TELL_CHILD(pid);
            }
        }
        exit(0);
}


所以会出现以下结果:


正确的实现为:

#include "apue.h"

static int count = 0;
int main(void)
{
        pid_t pid;
        TELL_WAIT();


        
        if((pid = fork()) < 0 ){
                err_sys("fork error");
        } else if (pid == 0) {
                count++;
                while(1){
                        TELL_WAIT();
                        WAIT_PARENT();
                        printf("output from child:");
                        printf("count=%d \n",count);
                        count=count+2;
                        TELL_PARENT(getppid());
                }
                exit(0);
        }
        else{
            printf("Output from parent:");
            printf("count=%d\n",count);
            TELL_CHILD(pid);//父进程一定要现执行一次,然后通知子进程,否则父子进程会永远互相等待
            while(1){
                 sleep(2);
                 TELL_WAIT();
                 WAIT_CHILD();
                 printf("output from parent:");
                 count=count+2;
                 printf("count=%d\n",count);
                 TELL_CHILD(pid);
            }
        }
        exit(0);
}
结果如下:



2、写文件实现

fork的一个特性是父进程所有的打开文件描述符file_struct都被复制到子进程中,父子进程的每个相同的打开描述符共享一个文件表项如图

这种共享的方式使父、子进程对同一个文件使用了同一个文件偏移量。如果父、子进程写到同一个文件描述符,但有没有任何形式的同步,那么它们的输出就会相互混合。在fork之后处理文件描述符有两种常见的情况:

1)父进程等待子进程完成。在这种情况下,父进程无须对其描述符做任何处理。当子进程终止之后,它曾进行过读、写的人一个共享描述符的文件偏移量已经执行了相应的更新。

2)父、子进程各自执行不同的程序段。这种情况下,在fork之后,父、子进程各自关闭它们不需使用的文件描述符,这样就不会干扰对方使用的文件描述符。这种方式是网络服务进程中常用的方式。



#include "apue.h"
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

const char *str_parent="output from parent";
const char *str_child="output from child";

static int count = 0;

void print(int fd,const char*str)
{
   char str_count[5];
   write(fd,str,strlen(str));
   sprintf(str_count,":%d\n",count);
   write(fd,str_count,strlen(str_count));

}

int main(void)
{
        pid_t pid;
        int fd;         

        fd=open("./test.txt",O_RDWR|O_CREAT|O_TRUNC|O_SYNC,S_IRUSR|S_IWUSR);
        TELL_WAIT();

        
        print(fd,str_parent);
        TELL_CHILD(pid);

        
        if((pid = fork()) < 0 ){
                err_sys("fork error");
        } else if (pid == 0) {
                count++;
                print(fd,str_child);
                while(1){
                        TELL_WAIT();
                        WAIT_PARENT();
                        count=count+2;
                        print(fd,str_child);
                        TELL_PARENT(getppid());
                }
                exit(0);
        }
        else{
            while(1){
                 sleep(2);
                 TELL_WAIT();
                 WAIT_CHILD();
                 count=count+2;
                 print(fd,str_parent);
                 TELL_CHILD(pid);
            }
        }
        close(fd);
        exit(0);
}




附上tellwait.c

#include "apue.h"

static volatile sig_atomic_t sigflag; /* set nonzero by sig handler */
static sigset_t newmask, oldmask, zeromask;

static void
sig_usr(int signo)	/* one signal handler for SIGUSR1 and SIGUSR2 */
{
	sigflag = 1;
}

void
TELL_WAIT(void)
{
	if (signal(SIGUSR1, sig_usr) == SIG_ERR)
		err_sys("signal(SIGUSR1) error");
	if (signal(SIGUSR2, sig_usr) == SIG_ERR)
		err_sys("signal(SIGUSR2) error");
	sigemptyset(&zeromask);
	sigemptyset(&newmask);
	sigaddset(&newmask, SIGUSR1);
	sigaddset(&newmask, SIGUSR2);

	/* Block SIGUSR1 and SIGUSR2, and save current signal mask */
	if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0)
		err_sys("SIG_BLOCK error");
}

void
TELL_PARENT(pid_t pid)
{
	kill(pid, SIGUSR2);		/* tell parent we're done */
}

void
WAIT_PARENT(void)
{
	while (sigflag == 0)
		sigsuspend(&zeromask);	/* and wait for parent */
	sigflag = 0;

	/* Reset signal mask to original value */
	if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
		err_sys("SIG_SETMASK error");
}

void
TELL_CHILD(pid_t pid)
{
	kill(pid, SIGUSR1);			/* tell child we're done */
}

void
WAIT_CHILD(void)
{
	while (sigflag == 0)
		sigsuspend(&zeromask);	/* and wait for child */
	sigflag = 0;

	/* Reset signal mask to original value */
	if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
		err_sys("SIG_SETMASK error");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值