0

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);
}
Poncjusz
  • 11
  • 1
  • 6

1 Answers1

0

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;
}
PeterT
  • 7,981
  • 1
  • 26
  • 34
  • Yes, I'm sorry. I need creat master and slave process. Can you show me how to divide this? – Poncjusz Oct 28 '18 at 16:18
  • @Poncjusz if you want to send one end of the unnamed pipe to another process you can use the various methods [described here](https://stackoverflow.com/questions/2358684/can-i-share-a-file-descriptor-to-another-process-on-linux-or-are-they-local-to-t). How exactly do you imagine the two processes being created without fork? If you can give me an example then I might be able to give you a specific method of sharing a pipe. – PeterT Oct 30 '18 at 20:26
  • @Poncjusz if you're looking for non-fork process creation there's [this question](https://unix.stackexchange.com/questions/136637/why-do-we-need-to-fork-to-create-new-processes) – PeterT Oct 30 '18 at 20:27