I want to try Pipe communication with child and parent process. Parent process write to pipe and child process read this but my program get error "write: Broken pipe". How can I change this code?
Thnks.
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <termios.h>
#include <errno.h>
#include <fcntl.h>
int main(void)
{
int i=0;
int child=5;
int fdp;
int fds[2];
int controlRead;
int controlWrite;
char pathName[30] = {"Trying Pipe Communication\n"};
if(pipe(fds) < 0)
{
perror("pipe");
exit(EXIT_FAILURE);
}
do{
if(child == 0)
{
close(fds[1]);
if( (controlRead = read(fds[0],pathName,sizeof(pathName)) ) <= 0)
{
perror("read");
exit(EXIT_FAILURE);
}
close(fds[0]);
printf("boru :%s\n",pathName);
wait();
}
else
{
printf("Parent process\n");
close(fds[0]);
if( (controlWrite = write(fds[1],&pathName,sizeof(pathName))) <= 0)
{
perror("write");
exit(EXIT_FAILURE);
}
close(fds[1]);
}
i++;
child = fork();
}while(i<3);
return 0;
}
error "write: Broken pipe". How can I change this code?
Don't break the pipe before you write to it. On the first pass through your do/while loop, the parent closes the read end and then writes to the remaining pipe fd. Kablam. EPIPE.
Your read loop shall count number of bytes read before closing the socket. Otherwise it is terminated too early.
Pipes are not packet transport, and single read/write is actually a series of operations. So when you are writing an array, it is wrong to assume it will come in one piece.
Related
The 'create_andWrite' function should create a pipe and write a string to it. The child process which is created in the main should read from the pipe.
I only worked with pipes in one method(e.g. read and write are both in main) before and I'm really struggling with this one.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int creat_and_write(FILE *fd, char *string) {}
int main() {
int fd[2];
creat_and_write();
int p = fork;
}
These are my functions signatures so far
Pipes are one way of unidirectional IPC, used usually with fork() to pass data in a sort of vertical hierarchy.
Hope the example below is clear. and spot the usage of the 2 functions.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define READ_END 0
#define WRITE_END 1
// pipe uses file descriptors to communicate between processes not pointers to files.
int creat_and_write(int *fd, char *string) {
// first and formost we need a pipe.
if (pipe(fd) == -1) {
perror("pipe error");
exit(1);
}
// now the fd contains 2 file descriptors, one for reading and one for writing to the pipe.
// we fork a child process which will inherit most internals including the pipe's file descriptors.
pid_t pid = fork();
if (pid == -1)
{
perror("fork error");
exit(1);
}
else if (pid == 0)
{
// we're at the child process.
// now we can write to the write end of the pipe
write(fd[WRITE_END], string, strlen(string));
// good practice to close done end of the pipe. for a full cleanup.
close(fd[WRITE_END]);
}
else
{
// we're at the parent process.
// now we can read from the read end of the pipe
char buffer[strlen(string)];
read(fd[READ_END], buffer, 100);
close(fd[READ_END]);
printf("now at the parent process: %s\n", buffer);
}
return 0;
}
int main() {
int fd[2];
creat_and_write(fd, "msg from child process");
return 0;
}
This is a C program where the Parent process tries to write a message to its child process using a simple pipe. The expected output is obtained.
According to the code, the parent calls wait() and waits until the child process exits(returns).
Also, the child process calls read(), which waits for something to be written through the other pipe end?
Thus, shouldn't both processes keep waiting for each other and cause a deadlock? How is it possible that the program works properly?
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MSGSIZE 16
char *msg1 = "Hello,Once";
char *msg2 = "Hello,Twice";
char *msg3 = "Hello,Thrice";
int main()
{
char buff[MSGSIZE];
int pi[2],pid,nbytes;
if(pipe(pi) < 0) _exit(1);
if((pid=fork()) > 0)
{
close(pi[0]);
write(pi[1],msg1,MSGSIZE);
write(pi[1],msg2,MSGSIZE);
write(pi[1],msg3,MSGSIZE);
close(pi[1]);
wait(NULL);
}
else
{
close(pi[1]);
while((nbytes = read(pi[0],buff,MSGSIZE)) > 0) printf("%s\n",buff);
printf("Reading Completed\n");
close(pi[0]);
if(nbytes != 0) _exit(2);
}
return 0;
}
I would like to create a named pipe in the parent process and after write a string to it in the child process and finally read this string in the parent process. When run the program I dont get back the prompt like still waiting for end of child process. Why the child process not finished?
Current output:
Expected output:
(picture created without multiprocesses)
My source code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
int main() {
int pipefd[2];
pid_t cpid;
char szoveg[32];
int fd, ret;
char buf[32];
buf[0]=0;
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(-1);
}
if (cpid == 0) {
printf("%d: Child process\n",getpid());
strcpy(buf,"Some text \0");
printf("%d:write to fifo: %s:%ld\n",getpid(),buf,strlen(buf));
write(fd,buf,strlen(buf));
exit(0);
} else {
printf("%d: Parent process\n",getpid());
ret=mkfifo("FifoName",00666);
if (ret == -1) {
perror("mkfifo()");
exit(-1);
}
fd=open("FifoName",O_RDWR);
if (fd == -1) {
perror("open() error!");
exit(-1);
}
wait(NULL);
ret=read(fd,buf,32);
printf("%d:read() Read %d bytes: %s\n",getpid(),ret,buf);
close(fd);
unlink("FifoName");
exit(0);
}
}
William Pursell right. The problem was the missing fd=open("FifoName",O_RDWR); line from child process.
I am trying to open a file with fopen, fork the current process and make the child process write something on the file; when the child process exits, the parents process should read the file's content, but it reads "null", even if the file has been correctly written. No errors are reported.
Here is my code:
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(int argc, char *argv[]){
FILE * sharedFile;
char *fileContent;
if((sharedFile = fopen("testFile.txt","w+")) == NULL){
fprintf(stderr,"Error while opening the file: %s",strerror(errno));
return 0;
}
pid_t pid = fork();
if(pid == 0){
//Child
fprintf(sharedFile,"%s",argv[1]);
exit(0);
}
else{
//Parent
wait(NULL);
if(fscanf(sharedFile,"%s",fileContent) < 0){
fprintf(stderr,"Error while reading file: %s",strerror(errno));
return 0;
}
fprintf(stdout,"File content: %s",fileContent); //Outputs "File content: (null)"
fclose(sharedFile);
}
}
Oddly, if I open again the file in the parent's code after the fork, the output is correct.
What could be the problem?
fileContent has not been allocated any space. Perhaps do this
char fileContent[101];
...
if (fscanf(sharedFile,"%100s",fileContent) != 1) // Prevent buffer overflows. Should return one when successful.
I want to make a simple program, that fork, and the child writes into the named pipe and the parent reads and displays from the named pipe.
The problem is that it enters the parent, does the first printf and then it gets weird, it doesn't do anything else, does not get to the second printf, it just ways for input in the console.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void main()
{
char t[100];
mkfifo("myfifo",777);
pid_t pid;
pid = fork();
if (pid==0)
{
//execl("fifo2","fifo2",(char*)0);
char r[100];
printf("scrie2->");
scanf("%s",r);
int fp;
fp = open("myfifo",O_WRONLY);
write(fp,r,99);
close(fp);
printf("exit kid \n");
exit(0);
} else
{
wait(0);
printf("entered parent \n"); // <- this it prints
// whats below this line apparently its not being executed
int fz; printf("1");
fz = open("myfifo",O_RDONLY); printf("2");
printf("fd: %d",fz);
char p[100];
int size;
printf("------");
//struct stat *info;
//stat("myfifo",info); printf("%d",(*info).st_size);
read(fz,p,99);
close(fz);
printf("%s",p);
printf("exit"); exit(0);
}
}
You really should be checking the return value on function calls for errors, especially mkfifo() and open().
Your call to wait() is going to cause problems in its current location. Opening a FIFO for reading normally blocks until some other process opens the same FIFO for writing, and vice versa1. The parent is waiting for the child to terminate and the child is waiting for a reader process, i.e., the parent, to connect to the FIFO.
1 - see note on open() below for using O_NONBLOCK with a FIFO
Moving the wait() call to just before the parent process exits along with changing the mode in the call to mkfifo() to 0666 seems to resolve some of your immediate problems.
It is also good practice to remove the FIFO when you are finished with it.
unlink("myfifo");
From the open() function documentation in IEEE Std 1003.1-2004:
When opening a FIFO with O_RDONLY or O_WRONLY set:
If O_NONBLOCK is set, an open() for reading-only shall return without delay. An open() for writing-only shall return an error if no process currently has the file open for reading.
If O_NONBLOCK is clear, an open() for reading-only shall block the calling thread until a thread opens the file for writing. An open() for writing-only shall block the calling thread until a thread opens the file for reading.
The following example is a combination of the code in your original question and the FIFO page of Beej's Guide to Unix IPC:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#define FIFO_NAME "myfifo"
int main(void)
{
char buf[256];
int num, fd;
pid_t pid;
if (mkfifo(FIFO_NAME, 0666) < 0)
perror("mkfifo");
pid = fork();
if (pid == 0)
{
printf("child - waiting for readers...\n");
if ((fd = open(FIFO_NAME, O_WRONLY)) < 0)
perror("child - open");
printf("child - got a reader -- type some stuff\n");
while (fgets(buf, sizeof(buf), stdin), !feof(stdin))
{
if ((num = write(fd, buf, strlen(buf))) < 0)
perror("child - write");
else
printf("child - wrote %d bytes\n", num);
}
close(fd);
exit(0);
}
else
{
printf("parent - waiting for writers...\n");
if ((fd = open(FIFO_NAME, O_RDONLY)) < 0)
perror("parent - open");
printf("parent - got a writer\n");
do
{
if ((num = read(fd, buf, sizeof(buf))) < 0)
perror("parent - read");
else
{
buf[num] = '\0';
printf("parent - read %d bytes: \"%s\"\n", num, buf);
}
} while (num > 0);
close(fd);
wait(0);
}
unlink(FIFO_NAME);
return 0;
}
This example was tested in Linux. Press Ctrl-D to terminate the program.
First of all, try fprintf to stderr instead of printf (to stdout)
The stderr is unbuffered.
Then you can tell what actually gets printed and what does not.
or at least add fflush before waiting for anything.