简体   繁体   中英

Simple pthreads and signal program on linux wont run

This program is supposed to

The parent simply waits indefinitely for any child to return (hint, waitpid). b. The child sets up two signal handlers (hint, signal) and goes to sleep for 5 minutes. i. The first signal handler listens for the USR1 signal, and upon receiving it: 1. Creates a thread (hint, pthread_create). a. Basically, all that the thread needs to do is “say hello” and sleep for 60 seconds. ii. The second signal handler listens for the USR2 signal, and upon receiving it: 1. Destroys the thread (hint, pthread_destroy).

My code compiles fine, just when I run it, absolutely nothing happens, not even the first printf which I put there as a test. Ive been staring at it for an hour and there are no errors, so why wont this run?

EDIT: This runs now, thanks charlie, however when it creates the thread, it outputs "[thread] sleeping for 1 m[thread] sleeping for 1 minute" and then ends, it never waits for the 2nd signal

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>

pthread_t thread;

void* temp()
{
    printf("[thread] hello professor\n");
    printf("[thread] sleeping for 1 minute\n");
    sleep(60);
}
void handle_USR1(int x)
{
    int s;
    printf("[signal] creating the thread\n");
    s = pthread_create(&thread, NULL, &temp, NULL);
}

void handle_USR2(int x)
{
    int s;
    printf("[signal] destroying the thread\n");
    s = pthread_cancel(thread);
}

int main(void)
{
    int status = 0;

    if(fork() != 0)
    {
     printf("[parent] waiting.....\n");
     waitpid(-1, &status, 0);
    }
    else
    {
     printf("[child] to create the thread: kill -USR1 %d\n", getpid());
     printf("[child] to end the thread: kill -USR2 %d\n", getpid());
     printf("[child] setting up signal handlers\n");

     signal(SIGUSR1, handle_USR1);
     signal(SIGUSR2, handle_USR2);

     printf("[child] waiting for signals\n");
     sleep(300);
    }
    return (0);
}

Add a newline "\\n" to all your printf's. Without it, stdout will not flush and it will appear your program is not working even though it is.

Also, checking fork() for failure is a good idea. fork() returns -1 on failure and sets errno.

I landed on this question while searching something else and realized your program would terminate as soon as SIGUSR1 signal is processed. You need to wait for your thread like you're waiting for child process by issuing pthread_join

void handle_USR1(int x) { int s; printf("[signal] creating the thread\\n"); s = pthread_create(&thread, NULL, &temp, NULL); pthread_join(thread, NULL); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM