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;
}

多写多练加油!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章