I can't get the output of another programme which i want to execute in the subprocess with system call "execvp" from "info.output", but when i write the above code in another file (like "wc.c"), it recovers normal.
So, i want to know whether i write wrong code or the book with something wrong.
all code i write:
p2.c
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "string.h"
#include "sys/wait.h"
#include "fcntl.h"
int main(int argc, char **argv){
printf("hello world (pid:%d)\n", (int)getpid());
int rc = fork();
if(rc < 0){
fprintf(stderr, "fork failed\n");
exit(1);
}else if(rc == 0){
printf("hello, I am child (pid:%d)\n", (int)getpid());
//if i write them here, i can't get output from info.output
//close(STDOUT_FILENO);
//open("./info.output", O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU);
char *myargs[3];
myargs[0] = strdup("./test");
if(myargs[0] == NULL){
fprintf(stderr, "malloc failed");
}
myargs[1] = strdup("--parameter");
if(myargs[1] == NULL){
fprintf(stderr, "malloc failed");
}
myargs[2] = NULL;
execvp(myargs[0], myargs);
printf("this statement shouldn't be executed");
}else{
//wait subprocess to finish, return pid of subprocess
int wc = wait(NULL);
printf("%d\n", wc);
printf("hello, I am parent of %d (pid:%d)\n", rc, (int)getpid());
}
return 0;
}
test.c
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "string.h"
#include "sys/wait.h"
#include "fcntl.h"
int main(int argc, char **argv){
if(argc == 1){
fprintf(stderr, "need a argument but no parameter");
exit(1);
}
//when i write them here, it's normal
close(STDOUT_FILENO);
open("./info.output", O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU);
for(int i = 1; i < argc; i++){
printf("%s\n", argv[i]);
}
return 0;
}
When I write code in "p4.c" like:
I can't get the output of another programme which i want to execute in the subprocess with system call "execvp" from "info.output", but when i write the above code in another file (like "wc.c"), it recovers normal. So, i want to know whether i write wrong code or the book with something wrong.
all code i write: p2.c
test.c