c - 如何在 C 程序中启动和终止进程(命令 shell)?

标签 c shell command-line arduino

我正在使用 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/

相关文章:

linux - 在 bash 脚本中发出回显变量

command-line - CMD:将所有屏幕内容导出到文本文件

node.js - 无法安装 Node.js 的 LTS 版本

编译AVX2程序

c - C 是否支持可选的空参数?

c - 错误: expected declaration specifiers or ‘...’ before ‘stdin’

javascript - MongoDB shell脚本使用投影格式化日期并获取本地时间

linux - 如何在 Bash 脚本的循环中添加超过 1 个数字?

iphone - plist实用程序在iPhone应用程序中转换info.plist

c++ - Node是什么样的类型?