我在下面有一個腳本,它指示將來自/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