Linux system() API [closed]
Can anybody tell me the output of the below code, whether "bye" will be printed or not?
#include <stdio.h>
int main()
{
system("ls -l");
printf("bye");
return 0;
}
man system
says:
int system(const char *command);
system()
executes a command specified incommand
by calling/bin/sh -c command
, and returns after the command has been completed.
And after system()
returned, your printf
will be executed.
Yes, it will be printed.
Why don't you compile it and test it for yourself? Cut and paste what you've written to a file, e.g. foo.c, and then do the following
gcc -o foo foo.c
./foo
As there is no newline character after your printf("bye") it will end up at the start of your current line; putting printf("bye\n") instead will be a little more clear.
Why wouldn't it? There's no conditional statement, so every part of the code will be executed.
It will print the output of the command provided by system and then print "bye"
The program is going to execute ls -l
just fine.
Also, "bye" should indeed be printed. However, since you have not included a '\n' character you will only be seeing it with your prompt appended to it.
Also, if you are not seeing it, then for some reason your output is not flushing when the program exits. Adding a '\n' character may very well fix that issue if that is what you are seeing.
It all depends upon the free memory. You will need to check return value of the system command.it returns 0 on success. Your printf statement will be called but not sure that system command will always success.
Thanks, Neel
精彩评论