I don't understand what I'm doing wrong. I'm learning about processes and right here I have to use one program this one:
int main(int argc, char **argv) {
pid_t pid;
if (argc != 4) {
printf("usage: %s <nom_du_programme_calcul> <operande_1> <operande_2>\n", argv[0]0);
exit(10);
}
switch(pid=fork()) {
case -1:
printf("fork impossible...\n");
exit(5);
case 0:
execlp(argv[1], argv[1], argv[2], argv[3], NULL);
printf("Recouvrement du code de %s impossible...", argv[1]);
exit(15);
default:
wait(NULL);
}
return 0;
}
and this one has to execute another program thanks to the child processes, just a program to execute an add.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int somme;
if (argc != 3) {
printf("usage: %s <operande_1> <operande_2>\n",
argv[0]);
exit(EXIT_FAILURE);
}
somme=atoi(argv[1]) atoi(argv[2]);
printf("%s %s = %d\n", argv[1], argv[2], somme);
}
Then I compile the first one as "recouvre" and the second one as "calcul" and I use this line for the execution:
./recouvre calcul 2 3
Apparently, something is wrong because the add doesn't work and I get my error msg saying that the recovery code (so the add one) doesn't work and it might be an error with the argv[], I think. But I don't see what I'm doing wrong.
CodePudding user response:
Converting comments into an answer.
Does it work (better) if you use:
./recouvre ./calcul 2 3
to run the command? There's a moderate chance that the current directory (.
) is not on your PATH, in which case the calcul
program won't be found. Using execl()
instead of execlp()
might well work with the original command line, too, under the "PATH missing .
(current directory)" hypothesis.
Mostly tangentially:
- Error messages should be reported to stderr, not stdout.
- Which C standard are you compiling with? With C90, you're not guaranteed an exit status in the child process because you don't explicitly use
return 0;
or something equivalent at the end. With later standards, you can get away with omitting that (the effect is as ifmain()
ended withreturn 0;
), but IMNSHO it is bad practice to do so. - What exactly is the error message you get?
- On some systems, using
NULL
rather than(char *)NULL
or(char *)0
as the last argument toexeclp()
might be a problem. In my estimation, it is unlikely to be the cause of your trouble.