I have a script below, that directs the redirects the data coming in from /dev/ttyUSB1
to a file.
#!/bin/bash
# start minicom with file name of todays date
cat /dev/ttyUSB1 > ~/serial_logs/$1.txt &
I call this script from a c program using system()
, which creates a file with the current date and time.
//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);
However at a later time in the c program I need to kill this process. System()
doesn't return the PID of the cat
process.
I came across this post which suggests to use the function below, but it is not that clear to me how I use it.
My question essentially is what do I pass as the arguments to it?
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;
}