#include <unistd.h> #include <signal.h> #include <stdio.h> #include <stdlib.h>

int pid1, pid2;

int main() { int fd[2]; char outpipe[100], inpipe[100];

pipe(fd);   /*创建一个管道*/
while ((pid1 = fork()) == -1);

if (pid1 == 0) {
    lockf(fd[1], 1, 0);
    sprintf(outpipe, 'child 1 process is sending message!');
    /*把串放入数组outpipe中*/
    write(fd[1], outpipe, 50);     /*向管道写长为50字节的串*/
    sleep(5);                 /*自我阻塞5秒*/
    lockf(fd[1], 0, 0);
    exit(0);
} else {
    while ((pid2 = fork()) == -1);
    if (pid2 == 0) {
        lockf(fd[1], 1, 0);           /*互斥*/
        sprintf(outpipe, 'child 2 process is sending message!');
        write(fd[1], outpipe, 50);
        sleep(5);
        lockf(fd[1], 0, 0);
        exit(0);
    } else {
        wait(0);              /*同步*/
        read(fd[0], inpipe, 50);   /*从管道中读长为50字节的串*/
        printf('%s

', inpipe); wait(0); read(fd[0], inpipe, 50); printf('%s ', inpipe); exit(0); } } }

详细解释内容:这段代码创建了一个管道,然后创建了两个子进程。

第一个子进程向管道中写入一个字符串,然后阻塞5秒,最后退出。

第二个子进程也向管道中写入一个字符串,然后阻塞5秒,最后退出。

父进程等待两个子进程结束后,从管道中读取两个字符串并打印出来。

在子进程写入管道时,使用了互斥锁来保证写入的串不会被打断。

在父进程读取管道时,使用了wait函数来保证两个子进程都已经结束,然后依次读取两个串并打印出来。

C语言管道通信示例:使用互斥锁和同步机制

原文地址: https://www.cveoy.top/t/topic/jkKC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录