Understanding the behavior of system() function in C programming

I’m working with a C program that uses the system() function to execute shell commands. I wrote this simple test program and I’m not sure about its execution flow.

#include <stdio.h>

int main()
{
    system("ps -aux");
    printf("finished");
    return 0;
}

I’m wondering if the printf statement will actually execute after the system call completes. Will the text “finished” be displayed on the console? I need to understand how the program execution continues after calling system() with a shell command. Does the system() function block the program until the command finishes, or does it run asynchronously? Any help understanding this behavior would be great.

yep! system() blocks until the command completes, so your printf runs after. i’ve used this tons of times - it always waits. just test it out and you’ll see “finished” appears after the command output.

Yes, system() definitely waits for completion before moving on. I found this out the hard way debugging a backup script that seemed to hang - it was just waiting for a massive file transfer to finish. Here’s what happens: system() creates a subprocess and waits for it (basically uses waitpid() under the hood). Your printf will run normally after the ps command finishes, but heads up - the shell command’s output gets mixed with your program’s output since they’re both writing to the same terminal. If you need more control or want true async behavior, you’ll need fork() and exec() instead.

Yeah, system() is synchronous and blocks your program until the shell command finishes. So “finished” won’t print until after ps completes. I found this out the hard way building a file processor - my progress bars would freeze every time I called external utilities. The function also returns the command’s exit status if you need it. Just heads up that system() spawns a new shell, so there’s extra overhead vs direct system calls. Your printf will run normally once ps wraps up.