Unnamed pipe without fork in C - 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);
}

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

Related

how to use execlp() with redirected output

i tried to write c program in Unix environment that using execlp function.
the command is:
execlp("tsort","tsort","text.txt",">","1.txt",(char *)NULL);
syserr("execlp");
i am always gets the same error.
the error is:
tsort: extra operand `>'
what did i do wrong?
'>' is not a parameter, it is normally interpreted by a shell. If you want to achieve the same effect in C code, you have to do the same thing the shell normally does:
open a file (1.txt) for writing
fork() a new process
[in child] replace the stdout of the new process with the file's descriptor using dup2()
[in child] exec the command
Simplified example code for POSIX:
#define _POSIX_C_SOURCE 200101L
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
int outfd = open("1.txt", O_CREAT|O_WRONLY|O_TRUNC, 0644);
if (!outfd)
{
perror("open");
return EXIT_FAILURE;
}
pid_t pid = fork();
if (pid < 0)
{
close(outfd);
perror("fork");
return EXIT_FAILURE;
}
if (pid)
{
// child code
dup2(outfd, 1); // replace stdout
close(outfd);
// just a "useless cat" for simplicity:
execlp("cat", "cat", "redir.c", 0);
}
else
{
// parent code
close(outfd);
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status)) return WEXITSTATUS(status);
else return EXIT_FAILURE;
}
}
As per the comment: If you don't mind replacing your process with the called program, you don't even need to fork and the program becomes very short:
#define _POSIX_C_SOURCE 200101L
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
int outfd = open("1.txt", O_CREAT|O_WRONLY|O_TRUNC, 0644);
if (!outfd)
{
perror("open");
return EXIT_FAILURE;
}
dup2(outfd, 1); // replace stdout
close(outfd);
execlp("cat", "cat", "redir.c", 0);
}
This of course is not what an interactive shell does.

Printf fails to print in parent and child after fork

I'm trying to use date and wc with pipes on CentOS. I'm not able to printf that I'm in parent or child. Any help is appreciated.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <assert.h>
#include <time.h>
#include <stdlib.h>
#include <semaphore.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
/* pipe1.c - send information through pipe. */
void syserr(char* msg)
{
printf("%s", msg);
}
void child(int pfd[]){
dup2(pfd[1],1);
execl("/bin/date", "date", 0);
}
void main()
{
int pfd[2], i, pid;
char str[] = "Hello World!\n";
if (pipe(pfd) == -1)
syserr("pipe");
printf("pfd[0] = %d, pfd[1] = %d\n", pfd[0], pfd[1]);
pid=fork();
switch(pid) {
case -1:
syserr("fork");
case 0:
{
printf("I'm child'");
child(pfd);
}
default:{ /* parent only */
if(pid!=0)
{
printf("I'm parent'");
dup2(pfd[0],0); //input
execl("/bin/wc", "wc", 0);
}/*default*/
} /*switch*/
}
}
Remember that <stdio.h> is buffered, and stdout is generally line-buffered, at least when it is a terminal. See setvbuf(3)
So you should either end each of your printf format control string with a \n or call fflush(3) at appropriate places. In particular, do a fflush(NULL); before your fork and your execl.
Also use perror on failure (i.e. replace every call to syserr by perror) to understand how system calls are failing. See perror(3) & errno(3) & strerror(3).
BTW, your main is incorrectly declared. You should enable all warnings and debug info when compiling (e.g. compile with gcc -Wall -Wextra -g). Improve your code to get no more warnings. Then use the debugger gdb ...
Notice that to avoid zombie processes, your parent process should use some waiting system call like waitpid(2) or wait(2) or wait4(2)
Works now. I had to add close(pfd[0]); in child, and close(pfd[1]); in parent.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <assert.h>
#include <time.h>
#include <stdlib.h>
#include <semaphore.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
/* pipe1.c - send information through pipe. */
void child(int pfd[]){
printf("I'm in child func\n");
close(pfd[0]);
dup2(pfd[1],1);
execl("/bin/date", "date", 0);
}
int main(){
int pfd[2], pid;
if (pipe(pfd) == -1) perror("pipe");
printf("pfd[0] = %d, pfd[1] = %d\n", pfd[0], pfd[1]);
fflush(NULL);
pid=fork();
switch(pid) {
case -1:
perror("fork");
case 0:
{
printf("I'm child\n");
child(pfd);
}
default:{ /* parent only */
if(pid!=0){
printf("I'm daddy\n");
close(pfd[1]);
dup2(pfd[0],0); //input
execl("/bin/wc", "wc", 0);
}/*default*/
} /*switch*/
}
return 0;
}

C - Scanf not blocking for named pipe / FIFO

Usually when a program call a scanf it waits until something is available in stdin to read from it. I am currently making a fifo for input and another one for output that will be used by another process to write an read from a background proccess. But, the background process seem not to wait for any scanf in it, does anyone know why?
Here is the code:
Background:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
int main()
{
int out, in, err;
char *cFifo = "/tmp/out";
char *cInFifo = "/tmp/in";
mkfifo(cFifo, S_IRUSR|S_IWUSR);
mkfifo(cInFifo, S_IRUSR|S_IWUSR);
out = open(cFifo, O_RDWR|O_TRUNC|O_NONBLOCK);
in = open(cInFifo, O_RDWR|O_TRUNC|O_NONBLOCK);
dup2(out, STDOUT_FILENO);
dup2(out, STDERR_FILENO);
dup2(in, STDIN_FILENO);
scanf("%*c");
while(1)
{
scanf("%*c");
printf("Hello\n");
fflush(stdout);
}
return 0;
}
Foreground:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
int main()
{
int out, in;
size_t i = 0;
char bufOut[1024];
char *cFifo = "/tmp/out";
char *cFifoIn = "/tmp/in";
out = open(cFifo, O_RDONLY);
in = open(cFifoIn, O_WRONLY);
while(1)
{
i =0;
while(!i)
{
i = read(out, bufOut, 1024);
}
if(i)
write(STDOUT_FILENO, bufOut, i);
}
return 0;
}
I have already tried to force write on the new input fifo but the result is the same.
I already checked for errors, and everything return the expected values, no -1 or any other errors associated with each function

how to end redirected execlp in c

I try to redirect the exec function input, output result with pipe. This code works fine, however I can't exit the execlp function below, which always require new input, however I just want run it one time. How can stop it after first input.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#define ERR_EXIT(m) \
do { \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
int main(int argc, char *argv[])
{
int chi_pipe[2], par_pipe[2];
if (pipe(chi_pipe) == -1 || pipe(par_pipe) == -1)
ERR_EXIT("pipe error");
pid_t pid;
pid = fork();
if (pid == -1)
ERR_EXIT("fork error");
if (pid == 0)
{
close(chi_pipe[0]); // I don't read in channel 1
close(par_pipe[1]); // I don't write in channel 2
close(STDIN_FILENO);
dup(par_pipe[0]);
execlp("tr", "tr", "/a-z/", "/A-Z/", NULL);
close(chi_pipe[1]);
close(par_pipe[0]);
_exit(0);
}
close(par_pipe[0]);
close(chi_pipe[1]);
write(par_pipe[1], "haha\n", 5);
char buf[3024] = {0};
read(chi_pipe[0], buf, 1024*3);
printf("buf=%s", buf);
printf("\n");
close(par_pipe[1]);
close(chi_pipe[0]);
return 0;
}
I think you want this.
move the close up so the read can know that it won't get any more.
write(par_pipe[1], "haha\n", 5);
close(par_pipe[1]);
you seem to missing a dup for stdout in the child segment too,

IPC FIFO Producer-Consumer Deadlock

This is the producer.
// speak.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define FIFO_NAME "american_maid"
int main(void)
{
char s[300];
int num, fd;
mknod(FIFO_NAME, S_IFIFO | 0666, 0);
printf("waiting for readers...\n");
fd = open(FIFO_NAME, O_WRONLY);
printf("got a reader--type some stuff\n");
while (gets(s), !feof(stdin)) {
if ((num = write(fd, s, strlen(s))) == -1)
perror("write");
else
printf("speak: wrote %d bytes\n", num);
}
return 0;
}
And this is the consumer.
//tick.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define FIFO_NAME "american_maid"
int main(void)
{
char s[300];
int num, fd;
mknod(FIFO_NAME, S_IFIFO | 0666, 0);
printf("waiting for writers...\n");
fd = open(FIFO_NAME, O_RDONLY);
printf("got a writer\n");
do {
if ((num = read(fd, s, 300)) == -1)
perror("read");
else {
s[num] = '\0';
printf("tick: read %d bytes: \"%s\"\n", num, s);
}
} while (num > 0);
return 0;
}
When I run them, Producer outputs,
waiting for readers...
And consumer outputs,
waiting for writers...
speak doesn't find the reader, tick. As from the theory here I got that, open() (speak.c) will be keep blocked until open() (tick.c) is opened. And the vice versa. So I guess there a deadlock or something happening. I need a solution of this.
It looks like you have a race condition between the reader and the writer.
To fix this, you need a method of not launching the reader until the writer is "active". For this, I'd suggest making a pipe and writing to it when the writer is ready. Then, when reading from the read end of the fork succeeds, the fifo is prepared and the reader should work.
You need to use forks here because coordinating mutexes between a parent and a child process is non-trivial and properly done pipes is easier.
Also, you called mknod() twice. Granted, it'll return -1 with errno == EEXIST, but be more careful. To avoid this, make the reader and writer a function that takes a path as an argument.
Rewrite your writer as int speak(const char *fifo, int pipefd) and your reader as int tick(const char *fifo).
Then make a wrapper like this:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
const char fifo_name[] /* = ... */;
int speak(const char *fifo, int pipefd);
int tick(const char *fifo);
int main() {
int pipefd[2];
pipe(pipefd);
mknod(fifo_name, S_IFIFO | 0666, 0);
if (fork() == 0) {
close(pipefd[0]);
return speak(fifo_name, pipefd[1]);
} else {
close(pipefd[1]);
char foo;
read(pipefd[0], &foo, 1);
return tick(fifo_name);
}
}
Modify your writer to print a byte (of anything) to the passed fd after the fifo is created (i.e. right after the call to open(..., O_WRONLY)).
Don't use my code verbatim, as I've omitted error checking for the sake of brevity.
it runs ok in my env. and if reader and writer is ready, open will return. because open is blocked, so in my opinion, mknod function is success. May be you excute these two process at different path.

Resources