I'm using fork to make process tree here's the code:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
int main () {
pid_t pid;
printf("Parent of all: %ld\n",(long)getpid());
pid = fork();
if(pid == -1){
perror("fork failed");
exit(EXIT_FAILURE);
}
else if (pid == 0){
pid = fork();
printf("Child with id: %ld and its Parent id: %ld \n", (long)getpid(),(long)getppid());
if(pid > 0){
pid = fork();
printf("Child with id: %ld and its Parent id: %ld \n", (long)getpid(),(long)getppid());
_exit(EXIT_SUCCESS);
}
}
else{
int status;
waitpid(pid, &status, 0);
}
return EXIT_SUCCESS;
}
after else if the printf line passes to a child so i get the same thing printed twice as u can see in results here results can i somehow prevent this from happening?
When you call fork both the parent and child process will continue executing from the same point, which means they will both execute printf("child with id...).
Related
I need help in modifying this code. Right now, it creates a process, and then waits for its termination. After which, another process is created, and then it waits for its termination. I want to modify it so that it creates both processes at the same time and executes them parallel to each other. The code is:
#include <sys/types.h>
#include <stdio.h>
int main(int argc, char * argv[]) {
pid_t pid;
int status;
pid = fork();
if (pid != 0) {
while (pid != wait( & status));
} else {
sleep(5);
exit(5);
}
pid = fork();
if (pid != 0) {
while (pid != wait( & status));
} else {
sleep(1);
exit(1);
}
}
Here's code that should do the job:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
pid_t pid = fork();
if (pid != 0)
printf("Child 1 PID = %d\n", pid);
else
{
sleep(5);
exit(5);
}
pid = fork();
if (pid != 0)
{
printf("Child 2 PID = %d\n", pid);
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
printf("Child %d exited with status 0x%.4X\n", corpse, status);
}
else
{
sleep(1);
exit(1);
}
return 0;
}
One time when I ran it, I got the output:
Child 1 PID = 49582
Child 2 PID = 49583
Child 49583 exited with status 0x0100
Child 49582 exited with status 0x0500
If you preferred, you could move the wait() loop and its variable declarations after the if structures and immediately before the return 0; at the end. That would give you better symmetry. You could even wrap up the child creation phase into a function called twice:
static void procreate(int kidnum, int naptime)
{
int pid = fork();
if (pid != 0)
printf("Child %d PID = %d (nap time = %d)\n", kidnum, pid, naptime);
else
{
sleep(naptime);
exit(naptime);
}
}
and then in main() you'd just have two calls to procreate() and the wait loop:
int main(void)
{
procreate(1, 5);
procreate(2, 1);
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
printf("Child PID %d exited with status 0x%.4X\n", corpse, status);
return 0;
}
I have an assignment which gives me this code to transform into a code that makes the parent process wait for all children processes to finish.
PS: the first code has 4 processes and needs to use waitpid to solve this.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
pid_t p = fork();
pid_t k = fork();
if(p>0){
printf("p=%d: PID = %d\n", p, getpid());
sleep(45);
exit(0);
}
else if(p==0){
printf("p=%d: PID = %d\n", p, getpid());
exit(0);
}
else if(p<0){
printf("ERRO! p=%d\n", p);
exit(p);
}
}
I've tried this, but I think that this only works for only 1 child process and not for a lot of them.
int main(){
pid_t p = fork();
pid_t k = fork();
if(p<0){
printf("fodeu");
exit(p);
}
else if(p==0){
printf("");
exit(0);
}
else{
for(i=0;i<4;i++){
int returnstatus;
waitpid(p,&returnstatus,0);
if(returnstatus == 0){
printf("o processo filho correu normalmente");
}
else if(returnstatus == 1){
printf("o processo filho ardeu");
}
}
}
}
This won't do your assignment, but I hope it is advice enough to get
you going. The assignment appear to be a riddle around fork(), your
teacher has good taste :-)
fork() is different. It returns twice.
In the parent it returns the process ID of the created process.
In the child it returns 0; a process can always determine its PID using getpid()
Actually, the assignment is not good taste. Usually code using `fork()
never lets any branch escape into enclosing code to avoid complete
bullshit. Like so,
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid = fork();
if (pid == 0 /*child*/) {
printf("PID %d (child) doing work\n", pid);
sleep(5);
exit(0); // don't let it continue (leak) into parent code
}
else if (pid > 0 /*parent*/) {
int status;
pid_t terminated;
printf("PID %d (parent) waiting for child PID %d\n", getpid(), pid);
terminated = waitpid(pid, &status, 0);
if (terminated == -1) {
perror("waitpid");
exit(1);
}
if (WIFEXITED(status))
printf("child exited normally with status %d\n", WEXITSTATUS(status));
else
printf("hm. child died otherwise. see 'man waidpid' for more\n");
}
return 0;
}
With this in mind, look at these two innocent looking lines,
pid_t p = fork(); // two processes after this
pid_t k = fork(); // executed by **two** processes, again duplicating
So, after these two lines we have four processes executing the rest of
the code in parallel. This is the point where brains explode. What
does the leaked child of the k line do when it asks what p's value
is?
Look at the output of this little program, to see what's the effect of
leaking.
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main(){
printf("MAIN PID %d\n", getpid());
fork();
fork();
printf("PID %d, PPID %d\n", getpid(), getppid());
return 0;
}
This is one way to do it; there will be numerous others.
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
static void wait_for_kids(void);
int main(void)
{
pid_t p = fork();
pid_t k = fork();
if (p > 0)
{
printf("p=%d: PID = %d\n", p, getpid());
sleep(5);
wait_for_kids();
printf("%d: p = %5d, k = %5d - exiting\n", getpid(), p, k);
exit(0);
}
else if (p == 0)
{
printf("p=%d: PID = %d\n", p, getpid());
wait_for_kids();
printf("%d: p = %5d, k = %5d - exiting\n", getpid(), p, k);
exit(0);
}
else
{
printf("ERROR! p=%d\n", p);
wait_for_kids();
printf("%d: p = %5d, k = %5d - exiting\n", getpid(), p, k);
exit(p);
}
/*NOTREACHED*/
}
static void wait_for_kids(void)
{
int corpse;
int status;
int pid = getpid();
while ((corpse = waitpid(0, &status, 0)) > 0)
printf("%d: child %d exited with status 0x%.4X\n", pid, corpse, status);
}
Example output:
p=43445: PID = 43444
p=43445: PID = 43446
p=0: PID = 43445
p=0: PID = 43447
43447: p = 0, k = 0 - exiting
43445: child 43447 exited with status 0x0000
43445: p = 0, k = 43447 - exiting
43446: p = 43445, k = 0 - exiting
43444: child 43445 exited with status 0x0000
43444: child 43446 exited with status 0x0000
43444: p = 43445, k = 43446 - exiting
how i can write a c code to create the following process using fork() , and I must Use these functions : wait (0) , getpid() and getppid() to print the id and the parent process id for each process you create.
this is the the tree that I want to describe it
#include<sys/types.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
printf("the process id %d" , getpid());
pid_t pid1,pid2,pid3;
pid1=fork();
pid2=fork();
pid3=fork();
if((pid2 == 0)&&(pid3 == 0))
{
if (pid1 !=0)
fork();
}
printf("the process id %d" , getpid());
return 0;
}
fork() creates a subthread process.
int main ( ) {
fork();
printf("Current Process id: %d", getpid());
printf("Parent Process id: %d", getppid());
fork();
}
This will show an example of how to deal with threads using C in linux.
kindly,check this code please
#include<sys/types.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
printf("the process id %d" , getpid());
pid_t pid1,pid2,pid3;
pid1=fork();
if (pid 1==0)
pid2=fork();
pid3=fork();
if((pid2 == 0)&&(pid3 == 0))
{
if (pid1 !=0)
fork();
}
printf("the process id %d" , getpid());
return 0;
}
Here is the output ---
Parent: my pid is 4525
Parent: my parent's pid is 3350
parant started- 4525 3350
Before Fork
Before Fork
Child 4526 4525
In parent
---Parent End---
When I try to execute the below code ---
void main(int argc, char *argv[])
{
int status;
pid_t my_pid, parent_pid,child_pid;
my_pid = getpid();
parent_pid = getppid();
printf("\nParent: my pid is %d", my_pid);
printf("\nParent: my parent's pid is %d", parent_pid);
printf("\nparant started- %d %d",my_pid,parent_pid);
printf("\nBefore Fork");
if((child_pid = fork()) < 0 )
{
perror("fork failure");
exit(1);
}
if(child_pid == 0)
{
printf("\n Child %d %d\n",getpid(),getppid());
}
else
{
printf("\nIn parent");
wait(&status);
printf("\n---Parent End---\n");
}
}
Why is the Before Fork is printing twice?? Thanks
It's because you're not flushing the output buffer prior to the fork(). Change to:
printf("\nBefore Fork\n");
or:
printf("\nBefore Fork");
fflush(stdout);
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.