Pipe creation through functions - c

I was wondering if someone can help me modify my current code....
Currently it creates my process using fork() and takes a pointer to a function which executes that childs code block.
I wanted to play around with pipes and attempt to now have Process Y send its pid to Process X and then i want to send it back to the Main...
Heres what i have currently
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h> // exit
#include <fcntl.h>
#include <sys/wait.h>
void processX();
void processY();
pid_t addChild(void (*childPtr) (), int fileDes[2]) {
pid_t cpid;
if((cpid=fork()) == 0) {
pipe(fileDes);
childPtr(fileDes);
wait(NULL);
exit(0);
} else if (cpid < 0) {
printf("failed to fork");
exit(1);
} else {
}
return cpid;
}
void processY(int fileDes[2]) {
printf("Child Y[%d] Created of Parent X[%d]\n", getpid(), getppid());
printf("We are now going to write Y PID to process X\n");
pid_t a = getpid();
char buf[1024]; // child reads from pipe() to buffer
close(fileDes[0]); // close reading end of the pipe
write(fileDes[1], &a, sizeof(buf) / sizeof(int));
}
void processX(int fileDes[2]) {
printf("Child X[%d] Created of parent Main[%d]\n", getpid(), getppid());
int status;
pid_t Y = addChild(processY, fileDes);
wait(&status);
pid_t new_val = 5;
close(fileDes[1]); // closing the writing end of the pipe.
read(fileDes[0], &new_val, sizeof(new_val));
printf("Message read with number %d: \n", new_val);
}
int main() {
int status;
int fd[2];
printf("Main process[%d]\n", getpid());
pid_t root = addChild(processX, fd);
wait(&status);
printf("We are going to read from X to Main and then return the Value we got from Y\n");
return 0;
}
I dont know to create a pipe from Y - X and then X - Main....
Y---->send pid ----> X received Y pid ----- send new info to main --->Main print received data...

My answer i came up with
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h> // exit
#include <fcntl.h>
#include <sys/wait.h>
void processX();
void processY();
pid_t addChild(void (*childPtr) (), int fileDes[2], int backToMainFd[2]) {
pid_t cpid;
if(childPtr != *processX //prevents the the pipe from main to x from recreating
pipe(fileDes);
if((cpid=fork()) == 0) {
if(childPtr == *processX) {
childPtr(fileDes, backToMainFd);
} else {
childPtr(fileDes);
}
wait(NULL);
exit(0);
} else if (cpid < 0) {
printf("failed to fork");
exit(1);
} else {
}
return cpid;
}
void processY(int fileDes[2]) {
printf("[PROCESS Y]: Child Y[%d] Created of Parent X[%d]\n", getpid(), getppid());
pid_t a = getpid();
char buf[1024]; // child reads from pipe() to buffer
close(fileDes[0]); // close reading end of the pipe
write(fileDes[1], &a, sizeof(buf) / sizeof(int));
}
void processX(int fileDes[2], int BackToMainFd[2]) {
printf("[PROCESS X]: Child X[%d] Created of parent Main[%d]\n", getpid(), getppid());
int status;
pid_t Y = addChild(processY, fileDes, NULL);
wait(&status);
pid_t new_val = 5;
close(fileDes[1]); // closing the writing end of the pipe.
read(fileDes[0], &new_val, sizeof(new_val));
printf("[PROCESS X]: We got Ys' PID as:%d from [PROCESS Y]\n", new_val);
close(BackToMainFd[0]); // close reading end of the pipe
char buf[1024]; // child reads from pipe() to buffer
write(BackToMainFd[1], &new_val, sizeof(buf) / sizeof(pid_t));
}
int main() {
int status;
int fd[2];
int backToMainFD[2];
printf("Main process[%d]\n", getpid());
pipe(backToMainFD);
pid_t root = addChild(processX, fd, backToMainFD);
wait(&status);
pid_t new_val = 5;
close(backToMainFD[1]); // closing the writing end of the pipe.
read(backToMainFD[0], &new_val, sizeof(new_val));
printf("[MAIN]: We got Ys' PID as:%d from [PROCESS X]\n", new_val);
printf("Send sig kills too Y and root\n");
kill(new_val, SIGKILL);
kill(root, SIGKILL);
printf("Terminate program.\n");
return 0;
}

Related

How to fix data write or read using pipe in c program is giving wrong output?

I am trying to get an integer input in the child process and send it to the parent process using pipe()
but I receive garbage values every time in the parent process.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include<sys/wait.h>
int main(int argc, char *argv[])
{
pid_t pid;
int fd[2];
char *args[] = {"", NULL};
int cnum,pnum;
pid = fork();
if (pid < 0)
{
perror("fork");
exit(1);
}
if(pipe(fd) == -1)//fd[0] for read fd[1] for write
{
perror("pipe");
exit(1);
}
if(pid == 0)
{
close(fd[0]);
printf("\n**In the child process**\n");
printf("Enter Number : ");
scanf("%d",&cnum);
write(fd[1],&cnum,sizeof(int));
close(fd[1]);
}
else
{
wait(NULL);
close(fd[1]);
printf("\n**In the parent precess**\n");
read(fd[0],&pnum,sizeof(int));
close(fd[0]);
printf("Number recieved = %d\n",pnum);
printf("PID = %d\n", getpid());
execv("./sayHello", args);
printf("Error");
}
}
Output of the above code
**In the child process**
Enter Number : 212
**In the parent precess**
Number recieved = 1036468968
PID = 22528
Hillo Amol
PID = 22528
I give input of 212 but in parent 1036468968 received.
You call fork before you create the pipe FDs. After you call fork, the parent and the child both create their own pair of pipe FDs, and there's no shared pipe between them.
Create the pipe before you fork and it could work.
As drorfromthenegev suggest problem is arising due to I am calling pipe() after fork().
So I call pipe() first and the i call fork() and it works..
Workable solution
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include<sys/wait.h>
int main(int argc, char *argv[])
{
pid_t pid;
int fd[2];
char *args[] = {"", NULL};
int cnum,pnum;
if(pipe(fd) == -1)//fd[0] for read fd[1] for write
{
perror("pipe");
exit(1);
}
pid = fork();
if (pid < 0)
{
perror("fork");
exit(1);
}
if(pid == 0)
{
close(fd[0]);
printf("\n**In the child process**\n");
printf("Enter Number : ");
scanf("%d",&cnum);
write(fd[1],&cnum,sizeof(int));
close(fd[1]);
}
else
{
wait(NULL);
close(fd[1]);
printf("\n**In the parent precess**\n");
read(fd[0],&pnum,sizeof(int));
close(fd[0]);
printf("Number recieved = %d\n",pnum);
printf("PID = %d\n", getpid());
execv("./sayHello", args);
printf("Error");
}
}

how can I send a signal between a child and a parent processes in linux

I have two cods the first one is for the parent which sends a signal (SIGUSER1) to the child and when the child receive it he should print that he received it.
Parent code
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
void sighand(int);
int main()
{
int cpid, ppid;
ppid = getpid();
printf("My process ID is %d\n", ppid);
FILE *fp1;
fp1 = fopen("cpid.txt", "w+");
cpid = fork();
if ( cpid == 0 ) {
printf("I am the child => PID = %d\n", getpid());
}
else
printf("I am the parent => PID = %d, child ID = %d\n", getpid(), cpid);
fprintf(fp1, "%d\n", cpid);
// kill(cpid, SIGUSR1);//id, signal, send
sigset(SIGUSR2, sighand);
return 0;
}
void sighand(int the_sig){
if (the_sig == SIGUSR2){
printf("sigusr2 received");
exit(1);
}
}
Child code
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
void sighand1(int);
int main()
{
FILE *fp1;
int pid;
fp1 = fopen("cpid.txt", "r");
fscanf(fp1, "%d,", &pid);
sigset(SIGUSR1,sighand1);
while(1) {
printf("Waiting..");
sigpause(SIGUSR1);
}
return 0;
}
void sighand1(int the_sig)
{
if (the_sig == SIGUSR1){
printf("sigusr1 received");
exit(1);
}
}
When I start the code it prints that the process (child) was created then when I send a signal it wont do any thing the child stuck in a loop or the wait and the parent wont do anything can any one tell me where did i go wrong in my code or logic.
Your code has several problems:
You try to pass some pid through a file, but you can use the getppid() function (get parent id)
You have some child code, but it is not called
no signal is launched
So your code can be corrected this way:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
void parent_handler(int the_sig)
{
if (the_sig == SIGUSR2){
printf("sigusr2 received in parent\n");
}
}
void child_handler(int the_sig)
{
if (the_sig == SIGUSR1){
printf("sigusr1 received in child\n");
kill(getppid(), SIGUSR2);
exit(1);
}
}
int child_function()
{
/* prepare to receive signal */
sigset(SIGUSR1,child_handler);
while(1) {
printf("Waiting..");
fflush(stdout);
/* wait for signal */
sigpause(SIGUSR1);
}
return 0;
}
int main()
{
int cpid, ppid;
ppid = getpid();
printf("My process ID is %d\n", ppid);
cpid = fork();
if ( cpid == 0 ) {
printf("I am the child => PID = %d\n", getpid());
child_function();
return 0;
}
else
printf("I am the parent => PID = %d, child ID = %d\n", getpid(), cpid);
/* child will never reach this point */
sleep(1);
/* prepare parent to received signal */
sigset(SIGUSR2, parent_handler);
/* send signal to child */
kill(cpid, SIGUSR1);
sleep(1);
return 0;
}

read from a pipe is blocked after close writer

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char **argv) {
int childs[3];
for (int i = 0; i < 3; ++i) {
int p[2];
if (pipe(p) == -1) { perror("pipe"); exit(1); }
pid_t pid = fork();
if (pid) {
close(p[0]);
childs[i] = p[1];
}
else {
close(p[1]);
printf("child %d start\n", i + 1);
char buf[10];
buf[0] = 0;
int r;
if ((r = read(p[0], buf, 9)) == -1) { ... }
printf("child %d read %s (%d), finish\n", i + 1, buf, r);
sleep(2);
exit(0);
}
}
for (int i = 0; i < 3; ++i) {
// if (argc > 1) {
// write(childs[i], "42", 2);
// }
// ============== HERE >>>
close(childs[i]);
}
pid_t pid;
while ((pid = waitpid(-1, NULL, 0)) > 0) {
printf("child %d exited\n", pid);
}
return 0;
}
Output with comment:
child 1 start
child 2 start
child 3 start
child 3 read (0), finish
The next line is displayed after 2 seconds
child 2 read (0), finish
The next line is displayed after 2 seconds
child 1 read (0), finish
I do not write to the channel in the parent. Closing it, I want to give a signal to the child that will be waiting in the read.
It seems that there is a following. Сhild N expected finishes reading from the result 0, it's ok. Children 2 (N-1) and 1 are locked in a read to a child 3 is completed. Then the child 1 is similar will wait.
Why lock occur?
Child processes inherit open file descriptors from their parent. Your main process opens file descriptors in a loop (using pipe, keeping only the write ends). Child 1 inherits no descriptors (except for stdin/stdout/stderr); child 2 inherits childs[0] (the descriptor going to child 1); child 3 inherits childs[0] and childs[1] (the descriptors going to child 1 and 2).
read on a pipe blocks as long as any write descriptor is still open (because it could be used to send more data). So child 1 waits (because child 2 and child 3 still have an open write descriptor) and child 2 waits (because child 3 still has an open write descriptor); only child 3 sleeps and exits. This causes its file descriptors to close, which wakes up child 2. Then child 2 sleeps and exits, closing its file descriptors, which finally wakes up child 1.
If you want to avoid this behavior, you have to close the open file descriptors in each child:
else {
for (int j = 0; j < i; j++) {
close(childs[j]);
}
close(p[1]);
printf("child %d start\n", i + 1);
The write ends of the pipes are getting inherited by the children.
Since filedescriptor are ref-counted, the write end is only considered closed if all references to it are closed.
Below is your code, slightly refactored, with a fix added:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char **argv) {
int children_w[3];
for (int i = 0; i < 3; ++i) {
int p[2];
if (0>pipe(p))
{ perror("pipe"); exit(1); }
pid_t pid;
if(0> (pid= fork()))
{ perror("fork"); exit(1); }
if(pid==0) {
/* Fix -- close the leaked write ends */
int j;
for(j=0; j<i; j++)
close(children_w[j]);
/* end fix*/
close(p[1]);
printf("child %d start\n", i + 1);
char buf[10];
buf[0] = 0;
int r;
if ((r = read(p[0], buf, 9)) == -1) { perror("read");/*...*/ }
printf("child %d read %s (%d), finish\n", i + 1, buf, r);
sleep(2);
exit(0);
}
children_w[i] = p[1];
close(p[0]);
}
for (int i = 0; i < 3; ++i) {
// if (argc > 1) {
// write(childs[i], "42", 2);
// }
// ============== HERE >>>
close(children_w[i]);
}
pid_t pid;
while ((pid = waitpid(-1, NULL, 0)) > 0) {
printf("child %d exited\n", pid);
}
return 0;
}

Create child process, make parent of the child to transmit a file.How do i do this?

This is my code.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
int file,parentID,childID;
pid_t pid;
int main(int argc, char *argv[])
{
if( argc != 2 )
{
printf("ERROR ! You have not write an argument\n");
printf("ERROR ! You give more than one argument");
return 1;
}
file = open(argv[1], O_RDONLY); //open file
if(file<0) //test the file
{
printf("Error open file\n");
printf("ERROR : %s\n", strerror(errno));
return 1;
}
// ---------------------------------------------------------------------
pid = fork();
if( pid == -1) //error fork
{
printf("Error fork\n");
return 1;
}
if(pid == 0) // child process
{
childID = getpid();
printf("Child process %d\n",childID);
// if(childID %2 == 1)
// {
// parentID = getppid();
// printf("Process of father of this child= %d\n",parentID);
// }
}
if( pid == 1)
{
parentID = getppid();
printf("ParentProcess %d\n",parentID);
}
}
I have to write a program to create a child process.Depending on the parity of the child process , the parent should transmit to child a message through a file , the message being taken over and showed by the child process( if the child process is a number that is divizible with 2 it will say -"Good morning!" else "Good night!" ).The parent should wait for the final execution of the child to terminate.
I'm trying really hard to do this exercise and i can't find anywere to explain me how or what function/structure object should i use to do this.Above i tried but i failed , and i understand somehow how fork does but... please help me with this code , or suggest me were should i go to read to make this exercise .Sorry for my bad english spelling.
What documentation are you using for the system calls?
There are a number of ways to do this, but what you probably want to do is create a pipe, and then fork the process. Since a fork copies everything, and child processes inherit the environment, each process has a copy of the file descriptors for the pipe. You can then read/write based on the return value of fork().
int main(int argc, char *argv[])
{
int fd[2];
char in[128], out[128];
if( argc != 2 )
{
printf("ERROR ! You have not write an argument\n");
printf("ERROR ! You give more than one argument");
return 1;
}
if (pipe(fd) == -1)
return 1;
// ---------------------------------------------------------------------
pid = fork();
if (!pid)
read(fd[0], in, 128);
else
write(fd[1], out, strlen(out) + 1);
pipe(2)
note, you usually want to close the file descriptor you're not using for one way communication
I think this is the code.
#include <stdio.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void sighandler (int sig)
{
if (sig == SIGUSR1)
{
FILE *f;
char line[100];
f = fopen("file","r");
fgets(line, 100, f);
printf ("Procesul copil cu pid %d a primit mesajul %s", getpid(), line);
fclose(f);
}
}
int main ()
{
pid_t pid;
FILE * f;
pid = fork();
if (pid < 0)
{
perror ("Eroare la fork()");
return (1);
}
else
if (pid == 0)
{
signal (SIGUSR1, sighandler);
pause();
return 0;
}
else
{
if (pid % 2 == 0)
{
printf ("Notificam procesul fiu cu pid %d", pid);
f = fopen ("file","w");
fprintf (f,"Good morning!");
fclose(f);
kill (pid, SIGUSR1);
}
else
{
printf ("Notificam procesul fiu cu pid %d", pid);
f = fopen ("file","w");
fprintf (f,"Good night!");
fclose(f);
kill (pid, SIGUSR1);
}
}
wait(NULL);
return 0;
}

C pipe() and fork()

I have a problem with a simple program im making with fork and pipes for learning purpose. I want a child that send the ppid to the parent to output the value of ppid and do this twice. However,the result is two ppid output are the same.Why?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd[2]; /* for the pipe */
int n,pid,ppid,val;
int p[5],q[5];
if (pipe(fd) < 0) {
printf("Pipe creation error\n");
exit(1);
}
for(val=0;val<2;val++){
pid = fork();
if (pid < 0) {
printf("Fork failed\n");
exit(1);
} else if (pid == 0) { /* child */
ppid = getpid();
printf("child %d pid:%d \n",val+1,ppid);
write(fd[1], &ppid, sizeof(ppid));
sleep(1);
close(fd[1]);
} else { /* parent */
//printf("Parent: pid: ");
close(fd[1]);
printf("%d \n",val+1);
sleep(1);
n = read(fd[0], &ppid ,sizeof(ppid));
printf("%d \n",ppid);
// fflush(stdout);
close(fd[0]);
wait(NULL);
// printf("<parent> I have completed!\n");
exit(0);
}
}
}
There may be potential problem in the program design. Since the parent waits for the child
in the first iteration, the child executes the for loop for val=1 and spawns another process
through fork. Eventually there are three process of which two of them will have the same pid
as one of them is executing the for twice.

Resources