gpt4 book ai didi

c - 终止在 shell 中激活进程的线程

转载 作者:太空宇宙 更新时间:2023-11-04 07:28:29 24 4
gpt4 key购买 nike

使用 pthreads,我创建了一个通过 shell 进行录音的线程:

void *thread_function(void *arg) {

system("arecord data.wav");

}

但是,当我调用 pthread_cancel(&thread_ID); 来终止线程时,录音机仍会自行工作(当然,直到我终止整个 C 程序)。

如何停止执行系统调用的 pthread?提前致谢!

最佳答案

您的线程启动函数应执行以下操作:

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);

具有清理功能,例如:

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

然后使用pthread_cancel 取消线程将杀死子进程。

关于c - 终止在 shell 中激活进程的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16111911/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com