writing to a pipe with a child and parent process - c

I am trying to create a child that calls sort. The parent sends data to the child through a pipe. My code compiles and runs, but there is no output. What am I doing wrong? Am I not closing the pipes correctly, writing the pipes or outputting the data correctly?
[eddit] On my system I need to call /bin/sort NOT /usr/bin/sort!
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <ctype.h>
int main(void){
int pipes[2];
pid_t pid;
FILE *stream;
if(pipe(pipes) == -1)
printf("could not create pipe\n");
switch(fork()){
case -1:
fprintf(stderr, "error forking\n");
break;
case 0:
dup2(pipes[0], STDIN_FILENO);
pid = getpid();
printf("in child, pid=%d\n");
if(close(pipes[1]) == -1)
fprintf(stderr,"err closing write end pid=%d\n", pid);
execl("/usr/bin/sort", "sort", (char*) NULL);
break;
default:
stream = fdopen(pipes[1], "w");
pid = getpid();
printf("in parent, pid=%d\n", pid);
if (stream == NULL)
fprintf(stderr, "could not create file streami\n");
if(close(pipes[0]) == -1)
printf("err closing read end pid=%d\n");
fputs("bob\n",stream);
fputs("cat\n",stream);
fputs("ace\n",stream);
fputs("dog\n",stream);
if(fclose(stream) == EOF)
fprintf(stderr, "error while closing stream\n");
break;
}
return 0;
}
[edit] Here is my working code. Thank you everyone
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void){
int pipes[2];
pid_t pid;
FILE *stream;
int stat;
if(pipe(pipes) == -1)
printf("could not create pipe\n");
switch(fork()){
case -1:
fprintf(stderr, "error forking\n");
break;
case 0:
dup2(pipes[0], STDIN_FILENO);
pid = getpid();
printf("in child, pid=%d\n", pid);
if(close(pipes[1]) == -1)
fprintf(stderr,"err closing write end pid=%d\n", pid);
if(close(pipes[0]) == -1)
fprintf(stderr,"err closing write end pid=%d\n", pid);
execl("/bin/sort", "sort", (char*) NULL);
exit(EXIT_FAILURE);
break;
default:
stream = fdopen(pipes[1], "w");
pid = getpid();
printf("in parent, pid=%d\n", pid);
if (stream == NULL)
fprintf(stderr, "could not create file streami\n");
if(close(pipes[0]) == -1)
printf("err closing read end pid=%d\n");
fputs("bob\n",stream);
fputs("cat\n",stream);
fputs("ace\n",stream);
fputs("dog\n",stream);
if(fclose(stream) == EOF)
fprintf(stderr, "error while closing stream\n");
break;
}
wait(&stat);
return 0;
}

You most certainly do not have enough close() calls in the code, which will lock the processes up.
Pseudo code:
Create pipe
Fork
In parent:
Close read end of pipe
Write data to be sorted down write end of pipe
Close write end of pipe
Wait for child to die
In child
Close write end of pipe
Duplicate read end of pipe to stdin
Close read end of pipe
Exec the sort program
Exit with an error if the exec returns
Note that the pseudo code ends up closing all four ends of the pipe - the two in the parent and the two in the child. If you don't do that, you will run into deadlock.

The only thing you're really missing is calling wait() or waitpid() at the end of the parent's code, so that it doesn't exit until the child has finished.

No arguments to sort command. Simply running an execl will not work.
A simple program to test would be:
int main(void){
execl("/bin/sort","/bin/sort","filename", (char*) NULL);
}
I will try to create a simple program for you to analyze the situation.
Here you go, try this code:
int main(void){
int pipefd[2];
pid_t pid = 0;
int status;
char data[100]={0};
int fildes[2] ;
int nbytes;
char buf[100]={0};
status = pipe(fildes);
if (status == -1 ) {
// handle eerrror.
}
switch (fork()) {
case -1: /* Handle error */
break;
case 0: /* Child - reads from pipe */
close(fildes[1]); /* Write end is unused */
nbytes = read(fildes[0], buf, 100); /* Get data from pipe */
fprintf(stderr,"Inside child val recieved is %s\n", buf);
/* At this point, a further read would see end of file ... */
execl("/bin/sort", "/bin/sort",buf, (char*) NULL);
close(fildes[0]); /* Finished with pipe */
exit(0);
default: /* Parent - writes to pipe */
close(fildes[0]); /* Read end is unused */
write(fildes[1], "file", strlen("file")); /* Write data on pipe */
close(fildes[1]); /* Child will see EOF */
exit(0);
}
}
Here "file" is a file which need to be sorted.
Hope you can customize it as per your need.
Enjoy..!!!

Related

why does my program get stuck in wait(NULL)?

I'm a c beginner and wrote a multiprocess program. I want to let my child process invoke strace and then pipe to the parent process so that parent process could print it.
But my parent progress seem to be getting stuck in wait(NULL); . I tried commenting code wait(NULL); and I got the output from my child process. I can't figure out why parent process keeping waiting. Hasn't the child process returned yet?
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char *argv[]) {
int pipefd[2];
pid_t pid;
char *exec_argv[] = { "/bin/strace", "-T", "tree", "/bin", NULL};
char *exec_envp[] = { "PATH=/bin", NULL };
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) { // child
close(pipefd[0]); /* close unused read end */
close(STDOUT_FILENO);
if (dup2(pipefd[1], STDERR_FILENO) == -1) {
perror("dup2");
exit(EXIT_FAILURE);
}
// invoke strace
execve(exec_argv[0], exec_argv, exec_envp);
perror(exec_argv[0]);
exit(EXIT_FAILURE);
} else { // parent
close(pipefd[1]); /* close unused write end */
if (dup2(pipefd[0], STDIN_FILENO) == -1) {
perror("dup2");
exit(EXIT_FAILURE);
}
printf("I'm parent!!!\n");
wait(NULL);
char *line = NULL;
size_t len;
while (getline(&line, &len, stdin) != -1) {
printf("%s", line);
}
free(line);
}
return 0;
}
You didn't close pipefd[0] in the parent.
You didn't close pipefd[1] in the child.
Another problem is that your code is susceptible to deadlocks. If the child writes enough to the pipe to fill it, it will block until it has space to accept more. And since the the pipe is not emptied until the child exits, the child will never unblock.
This is easy to fix: Read until EOF, then call wait to reap the child. In other words, move the wait so it's after the loop.

close pipe from parent and child process

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
int main() {
int p[2];
pipe(p);
if (fork() == 0) {
// child
/*#0*/ close(p[1]);
int received = -1;
while (read(p[0], &received, 4) != 0) {
printf("receive integer: %d\n", received);
received = -1;
}
printf("child exit\n");
exit(0);
} else {
// parent
/*#1*/ close(p[0]);
int sent = 42;
write(p[1], &sent, 4);
/*#2*/ close(p[1]);
printf("wait for child\n");
wait(0);
}
printf("finished\n");
}
I'm trying to understand fork and pipe in C. This program fork a child process, which receive an integer from parent process then exit when pipe closed. When executing, it prints
wait for child
receive integer: 42
child exit
finished
Yet the while loop got stuck after close(p[1]); at position #0 removed: that read would infinitely wait for an incoming variable from the pipe and never detect the pipe closed.
Can someone explain to me why p[1] has to be closed by both parent (position #2) and child (position #0) process?
Here is the code (from Linux manual page) with comments at the bottom of the code.
https://man7.org/linux/man-pages/man2/pipe.2.html
At /#2/ close(pipefd[1]), the comment states that "Reader will see EOF". It means there is nothing to read into child process anymore and then the statement "read(p[0], &received, 4)" will return 0. In the Linux manaul page https://man7.org/linux/man-pages/man2/read.2.html
states that "On success, the number of bytes read is returned (zero indicates end of file)"
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int
main(int argc, char *argv[])
{
int pipefd[2];
pid_t cpid;
char buf;
if (argc != 2) {
fprintf(stderr, "Usage: %s <string>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Child reads from pipe */
close(pipefd[1]); /* Close unused write end */
while (read(pipefd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "\n", 1);
close(pipefd[0]);
_exit(EXIT_SUCCESS);
} else {/* Parent writes argv[1] to pipe */
close(pipefd[0]); /* Close unused read end */
write(pipefd[1], argv[1], strlen(argv[1]));
/*#2*/ close(pipefd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}

write operation on pipe is always failing

I'm a bit new to pipes and concurrency, and have been frustrated with this problem for hours. I am struggling to understand why this write operation is constantly failing on my pipe. I am trying to have the child process write data through a pipe that will be received by the parent process. My current code is this:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 4096
int main() {
pid_t status;
int fd[2]; //The array of file descriptors
if (pipe(fd) == -1) {
printf("Error piping");
}
status = fork(); //Begin the fork process
switch (status) {
case -1:
perror("Error forking");
break;
case 0:
//Child process
close(fd[0]); //Only send data
char some_string[15] = "hi there";
if (write(fd[1], some_string, MAXSIZE) == -1) {
printf("Error writing to the pipe");
}
close(fd[1]); //Close write end
exit(1);
default:
close(fd[1]); //Only receive data
char readed[500] = "";
while(read(fd[0], readed, MAXSIZE) != 0) {
printf("read this %s\n", readed);
}
printf("Done reading");
close(fd[0]);
break;
}
return 1;
}
However, I constantly get the message "Error writing to pipe", meaning that the write operation has failed in the child process. Another interesting thing is that if I change some_string to a string literal instead, this code works fine with the exception that it never terminates and instead, the read operation in the parent process reads from STDIN! I don't understand why this could be happening, is it possible that we have a zombie child when parent executes so the pipe is "dead"? Or perhaps that the parent process terminates and we have an orphaned child? How can I avoid this and how does this explain the weird behaviour from the string literal instead? Any insights?
You told write() to read the data from out-of-range of the array and allowed read() to write the data read to out-of-range of the array. That is very bad.
Write only valid data and limit the length to read not to cause out-of-range access.
Try this:
#include <unistd.h>
#include <sys/types.h> /* add this to use pid_t */
#include <sys/wait.h> /* add this to use wait() */
#include <stdio.h>
#include <stdlib.h>
/* remove unused MAXSIZE */
int main() {
pid_t status;
int fd[2]; //The array of file descriptors
int st; /* variable for receiving the status */
if (pipe(fd) == -1) {
printf("Error piping");
return 1; /* return 1 when the execution failed */
}
status = fork(); //Begin the fork process
switch (status) {
case -1:
perror("Error forking");
return 1; /* return 1 when the execution failed */
break;
case 0:
//Child process
close(fd[0]); //Only send data
char some_string[15] = "hi there";
if (write(fd[1], some_string, sizeof(some_string)) == -1) {
printf("Error writing to the pipe");
}
close(fd[1]); //Close write end
exit(0); /* return 0 if the execution finished successfully */
default:
close(fd[1]); //Only receive data
char readed[500] = "";
while(read(fd[0], readed, sizeof(readed) - 1) != 0) { /* -1 for reserving space for terminating null-character */
printf("read this %s\n", readed);
}
printf("Done reading");
close(fd[0]);
wait(&st); /* wait for the child process to exit and release the data of the process */
break;
}
return 0; /* return 0 if the execution finished successfully */
}

Duplication of Piped output

Can someone please explain to me why my output has duplicates in it from the ls command. The normal operation of ls -l | sort does not give me a duplicated output so what could be the issue?
Essentially i'm trying to pipe the output from one command and enter it into another command. The program works so far, but the output is displaying duplicate data. Plus and explanation of why I would need to do a close after dup2 would be really helpful :)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
// function declarations
void executeLs(int data_pipe[]);
void executeSort(int data_pipe[]);
int main(){
int data_pipe[2]; // array storing the file descriptors
int childls_pid; // ls child process
int childSort_pid; // sort child process
int rc; // return vaue of the pipe
int child_status1;
int child_status2;
rc = pipe(data_pipe);
if(rc == -1){
perror("pipe");
exit(1);
}
childls_pid = fork();
childSort_pid = fork();
// Ls Child process
switch(childls_pid) {
case -1:
perror("fork childLs Error");
exit(1);
case 0:
// inside of child process
executeLs(data_pipe);
exit(0);
default:
break;
}
// Sort child process
switch(childSort_pid) {
case -1:
perror("fork childSort Error");
exit(1);
case 0:
executeSort(data_pipe);
exit(0);
default:
wait(&child_status2);
}
return 0;
}
void executeLs(int data_pipe[]){
// Closes the read file descriptor
close(data_pipe[0]);
dup2(data_pipe[1], STDOUT_FILENO);
// confused as to why this is necessary
close(data_pipe[1]);
execlp("ls", "ls", "-1", NULL);
}
void executeSort(int data_pipe[]){
// close the write file descriptor
close(data_pipe[1]);
dup2(data_pipe[0], STDIN_FILENO);
close(data_pipe[0]);
execlp("sort","sort", NULL);
}
The reason is that you're forking more processes than you intended. When you do:
childls_pid = fork();
childSort_pid = fork();
you're doing the second fork() in both the original parent process and the process created by the first fork(). So you now have the following process tree:
parent
childls
childSort
childSort
In both childls and childls->childSort, childls_pid is 0, so they both execute the case 0: clause that runs executeLs().
You need to move the second fork into code that only runs in the original parent. You can simply move it to after the first switch statement.
The reason you need to close the pipe FDs is because a pipe isn't really closed until all processes that have it open close it. If the child process has the write end of its pipe open, that will keep it from reading EOF on the pipe.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
// function declarations
void executeLs(int data_pipe[]);
void executeSort(int data_pipe[]);
int main(){
int data_pipe[2]; // array storing the file descriptors
int childls_pid; // ls child process
int childSort_pid; // sort child process
int rc; // return vaue of the pipe
int child_status1;
int child_status2;
rc = pipe(data_pipe);
if(rc == -1){
perror("pipe");
exit(1);
}
childls_pid = fork();
// Ls Child process
switch(childls_pid) {
case -1:
perror("fork childLs Error");
exit(1);
case 0:
// inside of child process
executeLs(data_pipe);
exit(0);
default:
break;
}
childSort_pid = fork();
// Sort child process
switch(childSort_pid) {
case -1:
perror("fork childSort Error");
exit(1);
case 0:
executeSort(data_pipe);
exit(0);
default:
wait(&child_status2);
}
return 0;
}
void executeLs(int data_pipe[]){
// Closes the read file descriptor
close(data_pipe[0]);
dup2(data_pipe[1], STDOUT_FILENO);
// confused as to why this is necessary
close(data_pipe[1]);
execlp("ls", "ls", "-1", NULL);
}
void executeSort(int data_pipe[]){
// close the write file descriptor
close(data_pipe[1]);
dup2(data_pipe[0], STDIN_FILENO);
close(data_pipe[0]);
execlp("sort","sort", NULL);
}

headache with named pipes and forks

I need to write program that have construction like this:
Parent makes fifo, then fork()
child 1 reads message from stdin and writes it to named pipe (FIFO)
then in parent process I need to create pipe (unnamed) and another fork()
child number 2 reades from FIFO, counts length of message and send number to parent via pipe(unnamed).
I created a simple program with one fork where child can communicate with parent:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define FIFO "/tmp/my_fifo"
int main()
{
pid_t fork_result;
int pipe_fd;
int res;
char writer[3];
char reader[3];
res = mkfifo(FIFO,0777);
if (res == 0)
{
printf("FIFO created!\n");
fork_result = fork();
if (fork_result == -1)
{
fprintf(stderr, "fork error");
exit(EXIT_FAILURE);
}
if (fork_result == 0)
{
printf("CHILD 1\n");
pipe_fd = open(FIFO, O_WRONLY | O_NONBLOCK);
scanf("%s", writer);
res = write(pipe_fd,writer,3);
if (res == -1)
{
fprintf(stderr,"error writing fifo\n");
exit(EXIT_FAILURE);
}
(void)close(pipe_fd);
exit(EXIT_SUCCESS);
}
else
{
printf("PARENT\n");
pipe_fd = open(FIFO, O_RDONLY);
res = read(pipe_fd, reader, 3);
printf("reader: 0: %c\n",reader[0]);
printf("reader: 1: %c\n",reader[1]);
printf("reader: 2: %c\n",reader[2]);
(void)close(res);
}
}
else
{
printf("deleting fifo... run program again!\n");
unlink(FIFO);
}
exit(EXIT_SUCCESS);
}
and it is working very well. So I created code that have architecture described above:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define FIFO "/tmp/my_fifo"
int main()
{
pid_t fork_result;
pid_t fork_result2;
int pipe_fd;
int res;
char writer[3];
char reader[3];
res = mkfifo(FIFO,0777);
if (res == 0)
{
printf("FIFO created!\n");
fork_result = fork();
if (fork_result == -1)
{
fprintf(stderr, "fork error");
exit(EXIT_FAILURE);
}
if (fork_result == 0)
{
printf("CHILD 1\n");
pipe_fd = open(FIFO, O_WRONLY | O_NONBLOCK);
scanf("%s", writer);
res = write(pipe_fd,writer,3);
if (res == -1)
{
fprintf(stderr,"error writing to fifo\n");
exit(EXIT_FAILURE);
}
(void)close(pipe_fd);
exit(EXIT_SUCCESS);
}
else
{
printf("PARENt 1\n");
//don't forget pipe!
fork_result = fork();
pipe_fd = open(FIFO, O_RDONLY);
if (fork_result == 0)
{
printf("CHILD 2\n");
res = read(pipe_fd, reader, 3);
printf("Odczytano: 0: %c\n",reader[0]);
printf("Odczytano: 1: %c\n",reader[1]);
printf("Odczytano: 2: %c\n",reader[2]);
(void)close(res);
}
}
}
else
{
printf("deleting fifo\n");
unlink(FIFO);
}
exit(EXIT_SUCCESS);
}
Running sequence is like this:
PARENT 1
CHILD 1
CHILD 2
so in Parent 1 I'm opening FIFO to read, in child 1 I'm writing to FIFO and child 2 should read it. I mean in code because when I run it I can't even write anything to FIFO. In blocks in scanf("%s", writer); which worked in first program.
Am I using open() correctly? Do I need to use getpid() somewhere? Why it's blocking when I try to write to fifo.
The problem is that CHILD1 is opening the fifo with O_NONBLOCK, which will fail (with EWOULDBLOCK or EAGAIN) if no other process has the fifo open for reading. Now in the first program, the parent continues running after the fork and opens the fifo for reading before the child gets going and opens the write end, so it works. But in the second case, the parent does an extra fork first, which slows it down just enough that CHILD1 gets to its open command before PARENT or CHILD2 has opened the fifo for reading, so the CHILD1 open fails.
Get rid of the O_NONBLOCK and it works just fine (though you do open the fifo for reading in both PARENT and CHILD2, which is probably not what you want).
You have another issue if you want to read from the keyboard. If you run this from the shell, PARENT will exit immediately (more or less), so the shell will go back to reading commands from the keyboard, which means that CHILD1 and the shell will be fighting over the input. If on the other hand, you do what you originally describe and have PARENT wait reading from a pipe from CHILD2, it should do what you want.
Isn't it because you use twice the same variable fork_result? As you created another variable fork_result2, which you don't use, it is probably unintended.
I don't know if this will solve your problem, but at least using fork_result2 at the second fork would make it easier to understand...

Resources