简体   繁体   English

终止在外壳中激活进程的线程

[英]Terminate a thread that activates a process in the shell

Using pthreads, I created a thread that does audio recording through shell: 使用pthreads,我创建了一个通过shell进行音频录制的线程:

void *thread_function(void *arg) {

system("arecord data.wav");

}

However, when I call pthread_cancel(&thread_ID); 但是,当我调用pthread_cancel(&thread_ID); to terminate the thread, the audio recorder still works on its own (Until I terminate the whole C program of course). 要终止线程,录音机仍然可以单独工作(直到我终止整个C程序)。

How do I stop a pthread that does a system call? 如何停止系统调用的pthread? Thanks in advance! 提前致谢!

Your thread start function should do the following: 您的线程启动函数应执行以下操作:

pid_t pid;
int status;
posix_spawnp(&pid, "arecord", 0, 0, (char *[]){"arecord", "data.wav", 0}, environ);
pthread_cleanup_push(cleanup, &pid);
while (waitpid(pid, &status, 0)<0 && errno==EINTR);
pthread_cleanup_pop(0);

With a cleanup function like: 具有如下清除功能:

static void cleanup(void *p)
{
    pid_t pid = *(pid_t *)p;
    kill(pid, SIGTERM);
    while (waitpid(pid, &status, 0)<0 && errno==EINTR);
}

Then cancelling the thread with pthread_cancel will kill the child process. 然后用pthread_cancel取消线程将杀死子进程。

system("arecord data.wav");

It will make a separate process (not a thread in your program) in your system, and terminating that thread will not affect that process. 它将在系统中创建一个单独的进程(不是程序中的线程),并且终止该线程不会影响该进程。 You should kill that process by another system call. 您应该通过另一个系统调用终止该进程。

However making the process with spawn* functions in non-waiting mode is a bit better than your way and in this case and you don't need an extra thread. 但是,在非等待模式下使用spawn *函数进行处理比您的方式要好一些,在这种情况下,您不需要额外的线程。

spawnl(P_NOWAIT, "arecord data.wav", .... );

But, killing the created process is ugly. 但是,杀死创建的进程很丑陋。

You can use pthread_kill to send a signal to a specific thread. 您可以使用pthread_kill将信号发送到特定线程。 The problem with thread cancellation is that it will be delayed until the program reaches a cancellation point ( see this answer ). 线程取消的问题在于,它将被延迟到程序到达取消点为止( 请参阅此答案 )。

If you do use pthread_kill then you can choose which signal to send. 如果确实使用pthread_kill则可以选择发送哪个信号。 I think it should be possible to end the thread with a kill signal which would then also end the child process spawned with system, although I'm not certain about that. 我认为应该有一个终止信号终止线程,然后终止一个由系统生成的子进程,尽管我不确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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