Search code examples
cprocesspipefork

Unnamed pipe without fork in C


I need create unnamed pipe in C without fork();

I have code with fork, but I can't find any information about unnamed pipe without fork. I read that this is an old solution, but it just needs it. Can anyone help me?

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define KOM "Message to parent\n"
int main()
{
    int potok_fd[2], count, status;
    char bufor[BUFSIZ];
    pipe(potok_fd);
    if (fork() == 0) {
        write(potok_fd[1], KOM, strlen(KOM));
        exit(0);
    }
    close(potok_fd[1]);
    while ((count = read(potok_fd[0], bufor, BUFSIZ)) > 0)
        write(1, bufor, count);
    wait(&status);
    return (status);
}

Solution

  • You should be more precise, what do you need it to do? Just sending a message to yourself within the same process doesn't make much sense.

    Anyway you can literally just not fork and do everything inside one process, it's just not really useful.

    #include <stdio.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    #define KOM "Message to parent\n"
    int main()
    {
        int potok_fd[2], count;
        char bufor[BUFSIZ];
        pipe(potok_fd);
        write(potok_fd[1], KOM, strlen(KOM));
        fcntl(potok_fd[0], F_SETFL, O_NONBLOCK);
        while ((count = read(potok_fd[0], bufor, BUFSIZ)) > 0)
            write(1, bufor, count);
        return 0;
    }