How to join a thread which have fork in it? - c

Following is the case.
{
...
pthread_create(thread_id, NULL, thread_fun, NULL);
pthread_join(thread_id, NULL);
...
}
void * thread_fun(void * arg)
{
if(fork())
{
printf("In Parent\n");
pthread_exit(NULL);
}
else
{
printf("In Child\n");
pthread_exit(NULL);
}
}
How to use pthread_join() in such a way that I can wait for both child and parent process in thread?

Put all threads into endless loops and then inspect the whole program state with ps, top, htop or similar tools. You will find that the child process only has a single thread, while the parent process has (at least) two.
Now, concerning your question how to use pthread_join() to wait for the child process, you simply can't, because you can only use it to wait for threads in the same process. You could wait for the child process to terminate (waitpid()).
If the above doesn't answer your question (it's a bit unclear because you want to "wait for both child and parent process", which is where I wonder from which process' context) take a step back instead and describe on a higher level what you're trying to achieve instead. In other words, this could be a so-called "XY Problem". Do a bit of research on that term, it's a good thing to learn and understand in any case.

There's basically two ways you can do it. You can either have the child thread wait for the child process before it exits, or you can pass the PID of the child process to the parent thread so it can wait for it. Here's the first approach:
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
void *thread_fun(void *arg);
int main(void) {
pthread_t thread;
pthread_create(&thread, NULL, thread_fun, NULL);
pthread_join(thread, NULL);
return 0;
}
void *thread_fun(void *arg) {
pid_t pid = fork();
if(pid) {
printf("In Parent\n");
waitpid(pid, NULL, 0);
pthread_exit(NULL);
} else {
printf("In Child\n");
exit(0);
}
}
And here's the second:
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
struct locked_pid {
sem_t sem;
pid_t pid;
};
void *thread_fun(void *arg);
int main(void) {
pthread_t thread;
struct locked_pid s;
sem_init(&s.sem, 0, 0);
pthread_create(&thread, NULL, thread_fun, &s);
sem_wait(&s.sem);
waitpid(s.pid, NULL, 0);
pthread_join(thread, NULL);
sem_destroy(&s.sem);
return 0;
}
void *thread_fun(void *arg) {
pid_t pid = fork();
if(pid) {
struct locked_pid *s = arg;
s->pid = pid;
sem_post(&s->sem);
printf("In Parent\n");
pthread_exit(NULL);
} else {
printf("In Child\n");
exit(0);
}
}
Note that the first is much simpler than the second. This is because in the second, you need a semaphore so that the parent process knows when the child PID gets written.
By the way, there's two things you should know about this code before you use it in anything important:
It doesn't have any error-checking, even though most of the functions it uses can fail.
POSIX says "If a multi-threaded process calls fork() ... the child process may only execute async-signal-safe operations until such time as one of the exec functions is called." This means that you shouldn't be doing printf("In Child\n");.

Related

How to use semaphores to control progress of 2 threads?

I learned the concept of semaphore. And I'm trying to implement it.
I've been trying to implement it for over 19 hours, but I can't do it, so I'm writing to ask for your help.
It checks the progress of the current two threads, just as it does with CV, and if both threads output entered, it can resume the subsequent operation.
Below is the full text of the code.
`
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>
void *child1(void *arg) {
printf("child thread 1 entered!\n");
// call semaphoreshere here
printf("child thread 1 exits!\n");
return NULL;
}
void *child2(void *arg) {
printf("child thread 2: entered!\n");
// call semaphores here
printf("child thread 2: exits\n");
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t p1, p2;
printf("parent thread: begin\n");
// init semaphores here
// // sem_init(&empty, 0, 0);
// // sem_init(&full, 0, 0); //Code tried but not working properly
pthread_create(&p1, NULL, child1, NULL);
pthread_create(&p2, NULL, child2, NULL);
pthread_join(p1, NULL);
pthread_join(p2, NULL);
printf("parent thread: end\n");
return 0;
}
`
Using ONLY TWO semaphores within the code, this attempts to control the thread's internal execution order so that both threads must output the ~~entered message before it can exit.
The execution result I want is as follows.
>>>
parent thread: begin
child thread 1 entered!
child thread 2: entered!
child thread 2: exits
child thread 1 exits!
parent thread: end
>>>
parent thread: begin
child thread 2 entered!
child thread 1: entered!
child thread 1: exits
child thread 2 exits!
parent thread: end
Like this, I want to implement only the role of monitoring each other to see if they've entered.
I'd appreciate your help.
thanks.
What you want to do (in semaphoore-thinking) is:
thread 1 waits till thread 2 is done before it exits.
thread 2 waits till thread 1 is done before it exits.
Which leads to the following code, which I modified a bit because I cannot stand global variables.
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>
typedef struct SharedContext_tag {
sem_t t1done;
sem_t t2done;
} SharedContext_t;
void *child1(void* arg) {
SharedContext_t* ctx = (SharedContext_t*) arg;
printf("child thread 1: entered!\n");
sem_post(&ctx->t1done);
sem_wait(&ctx->t2done);
printf("child thread 1 exits!\n");
return NULL;
}
void *child2(void* arg) {
SharedContext_t* ctx = (SharedContext_t*) arg;
printf("child thread 2: entered!\n");
sem_post(&ctx->t2done);
sem_wait(&ctx->t1done);
printf("child thread 2: exits!\n");
return NULL;
}
int main(int argc, const char* argv[]) {
pthread_t p1;
pthread_t p2;
SharedContext_t context;
sem_init(&context.t1done, 0, 0);
sem_init(&context.t2done, 0, 0);
printf("parent thread: begin\n");
pthread_create(&p1, NULL, child1, &context);
pthread_create(&p2, NULL, child2, &context);
pthread_join(p1, NULL);
pthread_join(p2, NULL);
printf("parent thread: end\n");
sem_close(&context.t1done);
sem_close(&context.t2done);
return 0;
}
On my machine at this time (being careful here!), the output is as required:
> ./sema
parent thread: begin
child thread 1: entered!
child thread 2: entered!
child thread 2: exits!
child thread 1 exits!
parent thread: end
In order for it to work, you need to link against the real-time library, librt. You do so by adding -pthread to your compile command.
> clang-13 -g -O0 -pthread -o sema sema.c

Semaphore not working properly

I am working on an assignment where we need to use semaphores in order to make the second print of the parent process wait until child executes first. It is first time using semaphores and I certainly understood how they work, however I think I have a problem with the initialising of sem_open().
By following this:
sem_t *sem_open(const char *name, int oflag);
I have created this:
sem_t *sem = sem_open("MYSEM", O_CREAT , 2);
However, when executing my sem_wait are ignored.This is my whole program:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
/* void ChildProcess(void) ChildProcess prototype */
/* void ParentProcess(void) ParentProcess prototype */
int main(int argc, char ** argv){
int pid;
pid = fork();
sem_t *sem = sem_open("MYSEM", O_CREAT , 2);
if (pid<0)
{
printf("Cannot create a child process");
exit(EXIT_FAILURE);
}
else if (pid==0)
{
printf("I am the child process. \n");
printf("The child process is done. \n");
sem_post(sem);
exit(EXIT_SUCCESS);
}
else
{
printf("I am the parent process. \n");
sem_wait(sem);
printf("The parent process is done. \n");
}
sem_destroy(sem);
exit (EXIT_SUCCESS);
}
and what is printing is:
I am the parent process.
The parent process is done.
I am the child process.
The child process is done.
and what should print is this:
I am the parent process.
I am the child process.
The child process is done.
The parent process is done.
in the parent : you create a semaphore, print a message and then wait for the semaphore.
in the child : you create a semaphore, print 2 messages, close the semaphone and exit.
now the parent can return from the wait.
See http://man7.org/linux/man-pages/man3/sem_wait.3.html for a trivial example

Pthread in C basic print

I'm writing a C program using Pthreads that creates a child thread. After creating the child thread, the parent thread should ouput two messages: "parent:begin" then it should print "parent:done". Same for child thread "child:begin" and "child:done". I have to make sure that the main thread prints his second message before the spawned (child) thread does. I have to following implementation but it only prints in the wrong order. I assume I should use flags. Any help would be appreciated.
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
volatile int done = 0;
void *child(void *arg) {
printf("child\n");
done = 1;
printf("child:done");
return NULL;
}
int main(int argc, char *argv[]) {
printf("parent: begin\n");
pthread_t c;
pthread_create(&c, NULL, child, NULL); // create child
while (done == 0); // spin
printf("parent: end\n");
return 0;
}
If you want the parent to print done first, then you should have the child thread spin until the parent is done. (Right now the parent spins waiting for the child.) You should also use pthread_join to make sure the child is done before the main thread returns:
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
volatile int done = 0;
void *child(void *arg) {
printf("child: begin\n");
while (done == 0); // spin
printf("child: done\n");
return NULL;
}
int main(int argc, char *argv[]) {
printf("parent: begin\n");
pthread_t c;
pthread_create(&c, NULL, child, NULL); // create child
printf("parent: done\n");
done = 1;
pthread_join(c, NULL);
return 0;
}
On my machine I get this output:
parent: begin
parent: done
child: begin
child: done
At the moment done is accessed without any synchronization by both threads. Proper way is to signal the child that the parent has completed printing using a conditional variable. This leads to data race.
Moreover, main() thread complete the execution before the does. In that case, the whole process will die. You can either call pthread_join() or simply exit the main thread with pthread_exit().
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
volatile int done = 0;
void *child(void *arg) {
printf("child\n");
pthread_mutex_lock(&mutex);
while(done == 0)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
printf("child:done");
return NULL;
}
int main(int argc, char *argv[]) {
printf("parent: begin\n");
pthread_t c;
pthread_create(&c, NULL, child, NULL); // create child
pthread_mutex_lock(&mutex);
done = 1;
printf("parent: end\n");
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}

kill() usage confusion in C

I have read the manual of kill, and I know that it is a system call for sending a signal. I write a simple multi process code, each child process will do the handler function if it catch a specified signal, which is SIGUSR1 in my code.
In my code, I have made 3 processes, each process will print out "yo" if they catch SIGUSR1 signal, but the output only print out one time or two time..? That really confuse me, thanks for your help!
Here is my code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <time.h>
#include <signal.h>
#include <sys/time.h>
#include <string.h>
#define N 3
int pid_id[N];
void handler (int signum)
{
printf("yo\n");
}
void child(int process_index)
{
struct sigaction sa;
/* Register */
memset(&sa, 0, sizeof(sa));
sa.sa_handler = handler;
sigaction(SIGUSR1, &sa, NULL);
printf("I am %d.\n", getpid());
pid_id[process_index] = getpid();
sleep(5);
exit(0);
}
int main()
{
int i, status;
pid_t pid[N];
pid_t pid_wait;
for (i=0;i<N;i++)
{
pid[i] = fork();
if (pid[i]==0)
{
child(i);
}
}
for (i=0;i<N;i++)
kill(pid_id[i], SIGUSR1);
for (i=0;i<N;i++)
{
do
{
pid_wait = waitpid(pid[i], &status, WNOHANG);
}while(pid_wait != pid[i]);
}
printf("all done\n");
return 0;
}
Remember that you're dealing with multiple processes now. Just because in the code it looks like you ran child before kill doesn't mean that it happened in that order. The order of execution is entirely dependent on how the OS schedules CPU time for these processes.
What's happening is that some of the child processes are killed before they can install their signal handler. This is an example of a race condition, much like the sort you get when starting new threads.
This can be solved by synchronising the parent with its children, so that it doesn't continue until all children have notified back that they have completed their necessary initialisation steps.

Can this C code create zombie processes?

I am wondering if the following code can create zombies:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(){
int i=1;
pid_t p;
p = fork();
i++;
if(p!=0){
waitpid(p, NULL, 0);
}
printf("%d\n",i);
return 0;
}
So, the parent process calls the waitpid for the child process, which returns immediately if the child has not already exited. So, no zombies can arise so far. But, if the child exits before return 0; command this would be a zombie then? I am actually confused about it. Should the waitpid be the last line of code before the program terminates? Any help would be appreciated. Thanks!
The child only becomes a zombie if it ends and the parent doesn't call wait*() as long as itself lives on.
In the moment the parent also ends the child is reaped by the init process which will take care to call wait*() on the child, so it will finally end and with this leave the zombie state and disappears from the process list.
To provoke the child created in your example code to become a zombie modify the code for example as follows:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void)
{
pid_t p = fork();
if (p != 0)
{
waitpid(p, NULL, 0); /* See if the child already had ended. */
sleep(1); /* Wait 1 seconds for the child to end. And eat away the SIGCHLD in case if arrived. */
pause(); /* Suspend main task. */
}
else
{
sleep(3); /* Just let the child live for some tme before becoming a zombie. */
}
return 0;
}
Due to the two following facts:
the child sleeps for 3s so the parent's call to waitpid() most probably will always fail
the default handling of SIGCHLD is to ignrore it.
the code above in fact is the same as:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void)
{
pid_t p = fork();
if (p != 0)
{
pause(); /* Suspend main task. */
}
else
{
sleep(3); /* Just let the child live for some tme before becoming a zombie. */
}
return 0;
}
I found a simple way to create a zombie process and test it using ps -e
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
void main()
{
pid_t pid;
pid = fork();
//parent sleeps while the child has exited
//not an orphan since parent still alive
//child will be still present in process table
if(pid==0)
{//child
exit(0);
}
else
{//parent
sleep(15);
}
}
run ps -e while within the 15 seconds...
you will see
6454 pts/2 00:00:00 a.out < defunct >

Resources