Reputation: 2967
I'm trying to build a simple C program, it basically asks for a file name to read or \0
to terminate the program.
My problem is when I input \0
it does not terminate, instead it keeps creating the fork and executing the other c program as child, any idea why?
int main (void)
{
printf("%d: Parent process ...\n",getpid());
char fileName[200];
printf ("%d: Enter an argument (or \\0 for none): ", getpid());
fflush(stdout);
scanf("%c", &fileName);
if(fileName == "\\0"){
exit(0);
}
int pid;
pid = fork();
if (pid == 0) {
printf("%d child\n",getpid());
execl ("./catter","catter", fileName,NULL);
}
sleep(6);
}
Upvotes: 0
Views: 56
Reputation: 122503
Your program has at least two problems, the first is %c
in scanf()
is used for single char
, not a string, you should use %s
instead, or better, use fgets()
for this job.
fgets(fileName, sizeof(fileName), stdin);
The second is that you are using ==
to compare strings, if(fileName == "\\0")
would NEVER be true. strcmp()
is the function you are looking for:
if (strcmp(fileName, "\\0") == 0)
Upvotes: 2