| k:arel 2006-02-27, 7:05 pm |
| I've made a C program1 that executes a commandline given command.
The program2 is called by another C(++) program with execl(), but that
doesn't matter here.
The problem is: i want to be able to cancel program1 by sending it a
signal with the kill() function.
Now, because program1 executes the command with bash -c, it gets
another PID on my machine and i lose my handler.
When i use system() to execute the command, i'm only able to stop it by
typing CTRL+C in the konsole (the system() commands ignores SIGINT
signals send with the kill command).
I've also tried using the popen() functie, which alows me to kill the
command execution with the kill command itself.
But when i call it from program2, i'm not able to kill it because,
again, multiple PIDs exist :-(
/* ****************************************
********** */
//simplified "program1.cpp"
int main(int argc, char* argv[]) {
int res;
ostringstream out;
char buffer[256];
FILE* fp;
//open pipe voor command execution
fp = popen(argv[1], "r"))
//keep reading from pipe untill process is finished
while( fgets(buffer, sizeof(buffer), fp) ) {
}
//close command pipe
res = pclose(fp);
return 0;
}
/* ****************************************
********** */
//program2 looks like this:
//...
pid = fork();
if( pid == 0 ) {
int res = execl( "program1", "program1", cmd, NULL );
} else {
//...
}
/* ****************************************
********** */
The overall question is: how do i get the PID of the process i run when
executing a given command so i can cancel it?
|