Linux网络编程--编写一个程序,开启2个进程,一个进程负责输出字符A,一个进程负责输出字符B,要求输出结果为ABABAB… 依次递推。

题目:

编写一个程序,开启2个进程,一个进程负责输出字符A,一个进程负责输出字符B,要求输出结果为ABABAB… 依次递推。

环境:Ubuntu+Codeblocks

首先是我最开始写的:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    pid_t pid;
    char c;

    pid=fork();

    if(-1 == pid){
        printf("Process creation failed.\n");
        return -1;
    }
    else if(pid == 0){
        c = 'B';
    }
    else{
        c = 'A';
        }
    //circle
    while(1){
        printf("%c",c);
        fflush(stdout);
        sleep(1);
    }
    return 0;
}

 但老师指出没有用到管道,不完美,后为:

然后是标准答案:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
    int fd[2];
    pid_t pid;
    pipe(fd);
    pid = fork();
    if( 0 == pid)
    {
        close(fd[0]);
        while(1)
        {
           printf("A\n");
           write(fd[1],"A",1);
            sleep(1);
        }
    }
    else
    {
        close(fd[1]);
        char c;
        while(1)
        {
           read(fd[0],&c,1);
           printf("B\n");
        }
    }
    return 0;
}

多写多练加油!!

猜你喜欢

转载自blog.csdn.net/MARS_098/article/details/105161848