找回密码
 注册
查看: 1156|回复: 2

看一下这个程序

[复制链接]
发表于 2006-3-31 21:44:41 | 显示全部楼层 |阅读模式
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>

void quit(char *buf)
{
    perror(buf);
    exit(EXIT_FAILURE);
}

int main()
{
    int fd;
    time_t tp;
    fd=mkfifo("fi",0644);
    if(fd<0)
        quit("mkfifo");
    int pid=fork();
    if(pid<0)
        quit("fork");
    else if(pid>0)
    {
        if((fd = open("fi",O_RDONLY,0644))<0)
            quit("parent open");
        char buf[PIPE_BUF-1];
        int i=read(fd,buf,PIPE_BUF-1);
        if(i>0)
            printf("parent read : %s",buf);
    }
    else
    {
        if((fd = open("fi",O_WRONLY,0644))<0)
            quit("child open");
        char buf1[PIPE_BUF-1];
        int j=sprintf(buf1,"%d send %s",getpid(),ctime(&tp));
        write(fd,buf1,j+1);
    }
    close(fd);
    exit(EXIT_SUCCESS);
}
我想实现两个进程同时对命名管道一读一写,应如何修改,现在这个程序已运行,就不动了 只能ctrl+c终止
发表于 2006-4-2 15:38:57 | 显示全部楼层
先把代码排版一下
回复

使用道具 举报

发表于 2006-4-2 23:10:46 | 显示全部楼层
举手之劳~~ indent 命令:)
[code:1]#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <unistd.h> // Add this line for compilation issues

void
quit(char *buf)
{
        perror(buf);
        exit(EXIT_FAILURE);
}

int
main()
{
        int             fd;
        time_t          tp;
        fd = mkfifo("fi", 0644);
        if (fd < 0)
                quit("mkfifo");
        int             pid = fork();
        if (pid < 0)
                quit("fork");
        else if (pid > 0) {
                if ((fd = open("fi", O_RDONLY, 0644)) < 0)
                        quit("parent open");
                char            buf[PIPE_BUF - 1];
                int             i = read(fd, buf, PIPE_BUF - 1);
                if (i > 0)
                        printf("parent read : %s", buf);
        } else {
                if ((fd = open("fi", O_WRONLY, 0644)) < 0)
                        quit("child open");
                char            buf1[PIPE_BUF - 1];
                int             j = sprintf(buf1, "%d send %s", getpid(), ctime(
&tp));
                write(fd, buf1, j + 1);
        }
        close(fd);
        exit(EXIT_SUCCESS);
}
[/code:1]
程序在 Linux 2.6.8 和 SunOS 5.9 分别测试通过。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

GMT+8, 2025-2-7 03:00 , Processed in 0.041161 second(s), 15 queries .

© 2001-2025 Discuz! Team. Powered by Discuz! X3.5.

快速回复 返回顶部 返回列表