我下面有一个脚本,它将将从 /dev/ttyUSB1
传入的数据重定向到文件。
#!/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;
}
最佳答案
我将什么作为参数传递给它?
该函数接受指向整数的指针 (int*
) 并写入这些整数地址,因此您需要有两个整数并像这样传递它们的地址:
int input, output; // input and output file descriptors
int pid = system2("script args", &input, &output);
关于c - 如何在c程序中获取使用system()启动的进程的PID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45348486/