我正在使用 arduino 将一些数据从热电偶存储到笔记本电脑(OSX)。我想在 C 程序上使用存储的数据,但我有一些疑问。
我有这个小例子:
include <stdio.h>
include <stdlib.h>
int main (void)
{
int a;
a=fork();
if(a==0)
{
system("cat /dev/cu.usbmodem1a21 - 9600 >> num.txt");
}
return 0;
}
我正在尝试将串行(arduino)重定向到某个文件,因此我使用fork
来复制该过程并在代码仍在执行时运行命令。然而,这是一个肮脏的解决方案,因为我需要使用控制台手动终止该进程。我想知道是否有办法在同一程序中使用 C 代码来终止进程。
提前致谢。
ps:我尝试使用 getpid() 并终止该进程,但我再次认为这是一个肮脏的解决方案。
最佳答案
无需调用 getpid() 来获取 pid。函数 fork() 在父进程中返回子进程的 pid,在子进程中返回 0。因此,您可以直接向子进程发送 SIGKILL。
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
int main()
{
pid_t pid;
pid = fork();
if (pid == 0) {
system("cat /dev/cu.usbmodem1a21 - 9600 >> num.txt");
} else {
/* ops */
kill(pid, SIGKILL);
}
return 0;
}
关于c - 如何在 C 程序中启动和终止进程(命令 shell)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21071489/