Linux--父子進程同步協作__Linux

來源:互聯網
上載者:User

以下代碼是父子進程交替列印變數counter的值。由於fork之後子進程會複製父進程的堆棧,訊號處理函數,訊號屏蔽字,在下面的程式會根據counter的不同初值進行分別。

#include <stdio.h>#include <signal.h>#include <unistd.h>#include <stdlib.h>#include <string.h>sigset_t newset, zeroset;static int counter = 1;static int sigFlag = 0;void sig_handler(int signo){if (signo == SIGUSR1 || signo == SIGUSR2){sigFlag = 1;}}void tell_wait(){sigemptyset(&newset);sigemptyset(&zeroset);sigaddset(&newset, SIGUSR1);sigaddset(&newset, SIGUSR2);struct sigaction action;action.sa_handler = sig_handler;sigemptyset(&action.sa_mask);action.sa_flags = 0;if (sigaction(SIGUSR1, &action, NULL) < 0){printf("sigaction error\n");exit(-1);}if (sigaction(SIGUSR2, &action, NULL) < 0){printf("sigaction error\n");exit(-1);}if (sigprocmask(SIG_BLOCK, &newset, NULL) < 0){printf("sigprocmask error\n");exit(-1);}}void tell_parent(pid_t pid){kill(pid, SIGUSR2);}void wait_parent(){while(sigFlag == 0){sigsuspend(&zeroset);}sigFlag = 0;if (sigprocmask(SIG_BLOCK, &newset, NULL) < 0){printf("set sigprocmask error\n");exit(-1);}}void tell_child(pid_t pid){kill(pid, SIGUSR1);}void wait_child(){while(sigFlag == 0){sigsuspend(&zeroset);}sigFlag = 0;if (sigprocmask(SIG_BLOCK, &newset, NULL) < 0){printf("set sigprocmask error\n");exit(-1);}}int main(int argc, char **argv){pid_t pid;tell_wait();if ((pid = fork()) < 0){perror("fork");return -1;}else if(pid == 0) //child{counter = 0;while(1){wait_parent();counter+=2;char line[128] = {0}; sprintf(line, "#========child: %d\n", counter);write(STDOUT_FILENO, line, strlen(line)); //printf("#========child: %d\n", counter);tell_parent(getppid());}}else{counter = -1;while(1){counter+=2;char line[128] = {0}; sprintf(line, "#===parent: %d\n", counter);write(STDOUT_FILENO, line, strlen(line)); //printf("#===parent: %d\n", counter);tell_child(pid);wait_child();}waitpid(pid, NULL, 0);}return 0;}


需要注意的地方是注釋的printf部分,使用printf將輸出(./a.out >> test)重新導向到檔案的時候,不會出現這種交替列印的結果。原因是,重新導向到的檔案是全緩衝,printf是帶緩衝的,會緩衝到一定程度才能從記憶體緩衝中輸出到檔案。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.