문제

i have written the following code to copy a string "hello world" to another char array using fork and pipes instead of using standard library functions or standard i/o streams. The program is compiling successfully but i am not getting any output. Even, the printf's output are not being shown.

# include <string.h>
# include <unistd.h>
# include <stdio.h>

char string[] = "hello world";

int main()

{

        int count, i;
        int toPar[2], toChild[2];
        char buf[256];
        pipe(toPar);
        pipe(toChild);

        if (fork() == 0)
        {
                printf("\n--- child process ---");
                close(0);
                dup(toChild[0]);
                close(1);
                dup(toPar[1]);
                close(toPar[1]);
                close(toChild[0]);
                close(toPar[0]);
                close(toChild[1]);
                for (;;)
                {
                        if ((count = read(0, buf, sizeof(buf))) == 0)
                                break;
                        printf("\nChild buf: %s", buf);
                        write(1, buf, count);
                }
        }

        printf("\n--- parent process ---");
        close(1);
        dup(toChild[1]);
        close(0);
        dup(toPar[0]);
        close(toPar[1]);
        close(toChild[0]);
        close(toPar[0]);
        close(toChild[1]);
        for (i = 0; i < 15; i++)
        {
                write(1, string, strlen(string));
                printf("\nParent buf: %s", buf);
                read(0, buf, sizeof(buf));
        }
        return 0;

   }
도움이 되었습니까?

해결책

Your printfs are writing to stdout - but in both the parent and child, you've redirected file descriptor 1 to a pipe, so that's where the printf output will go.

Instead of printf(...), use fprintf(stderr, ...) - then you'll be able to see the output, since stderr is still pointing to your terminal.

Note that you have a couple of bugs:

  • the child should call _exit(0) when it is done, otherwise it will drop into the parent code;
  • the write should use strlen(string) + 1, so that it writes the nul terminator.

다른 팁

Try adding a "\n", like printf("\nParent buf: %s\n", buf);

I'd guess that those pipes are doing blocking IO, so read will simply not return unless the pipe is closed by the other process. That, and printf doing buffered IO, prevents you from getting any output.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top