我正在练习使用 execv。我很好奇为什么用 execv() 启动的新程序中的 printf() 正在打印!字符在新行上?%s 之后的任何内容都会导致在新行上打印相同的结果,我不确定为什么。下面是我的代码和结果。谢谢!
我正在编译: gcc --std=c99 -o hello_world_driver hello_world_driver.c; gcc --std=c99 -o hello_world hello_world.c
//hello_world_driver.c file
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char * argv[])
{
char nameArr[50]; //used to hold users name
char * newargv[] = {NULL, NULL, NULL}; //this arr will be passed in order to use execv
printf("Please enter your name.\n");
fgets(nameArr, 50, stdin);
newargv[0] = argv[1];
newargv[1] = nameArr;
execv(newargv[0], newargv);
//next two lines executed only if there is an error with execv
perror("execv did not work!\n");
exit(EXIT_FAILURE);
}
//hello_world.c file
#include <stdio.h>
int main(int argc, char * argv[])
{
printf("Hello %s!", argv[1]);
return 0;
}
% ./hello_world_driver ./hello_world
Please enter your name.
Max
Hello Max
!%