我在下面有一个脚本,它指示将来自/dev/ttyUSB1
的数据重定向到文件。如何获得在c程序中使用system()启动的进程的PID
#!/bin/bash
# start minicom with file name of todays date
cat /dev/ttyUSB1 > ~/serial_logs/$1.txt &
我把这个脚本使用system()
一个C程序,它创建与当前日期和时间的文件。
//Get string with date & time
//Open minicom with logging to filename with date and time
strftime(s, sizeof(s), "%a%b%d%T", tm);
snprintf(buf, SM_BUF, "~/logging.sh %s",s);
system(buf);
但是在稍后的c程序中,我需要杀死这个进程。 System()
不返回cat
进程的PID。
我碰到过this post这暗示使用下面的函数,但是我不清楚我如何使用它。
我的问题基本上是我作为参数传递给它什么?
pid_t system2(const char * command, int * infp, int * outfp)
{
int p_stdin[2];
int p_stdout[2];
pid_t pid;
if (pipe(p_stdin) == -1)
return -1;
if (pipe(p_stdout) == -1) {
close(p_stdin[0]);
close(p_stdin[1]);
return -1;
}
pid = fork();
if (pid < 0) {
close(p_stdin[0]);
close(p_stdin[1]);
close(p_stdout[0]);
close(p_stdout[1]);
return pid;
} else if (pid == 0) {
close(p_stdin[1]);
dup2(p_stdin[0], 0);
close(p_stdout[0]);
dup2(p_stdout[1], 1);
dup2(::open("/dev/null", O_RDONLY), 2);
/// Close all other descriptors for the safety sake.
for (int i = 3; i < 4096; ++i)
::close(i);
setsid();
execl("/bin/sh", "sh", "-c", command, NULL);
_exit(1);
}
close(p_stdin[0]);
close(p_stdout[1]);
if (infp == NULL) {
close(p_stdin[1]);
} else {
*infp = p_stdin[1];
}
if (outfp == NULL) {
close(p_stdout[0]);
} else {
*outfp = p_stdout[0];
}
return pid;
}
重复这个https://stackoverflow.com/questions/22802902/how-to-get-pid-of-process-executed-with-system-command-in-c? – fghj
[如何获得用C++中的system()命令执行的进程的pid](https:// stackoverflow。com/questions/22802902 /如何获得进程的执行与系统命令在c) – fghj
@MarkPlotnick是的抱歉,我正在寻找猫进程的PID。 – riverrock