Synchronization in C with system calls

4.2k views Asked by At

I am doing something a bit weird but i want it fully synchronized. So i thought of asking your help. I have the following:

printf("My name is:");
system("echo syntax_Error");
printf("I am 17 yrs old\n");

this is quite abstract instead of echo I am executing a software that gives me an output, so execution time is unpredictable, but the order is the same. I want a printf then system call then printf such that they would come aligned as such

My name is syntax_Error I am 17 yrs old\n

I tried this order without locks but it didn't work which is quite obvious, or if it did sometimes it is unpredictable. I am new to synchronization structures so I would like your input.

cheers!=)

3

There are 3 answers

0
David Victor On BEST ANSWER

If you're thinking about threading and mutual exclusion (synchronisation) in C then look at POSIX threads. (man pthread).

As others have said to get your strings in the right order flush stdout. If you're on an OS with 'echo' that supports -n (no newline) this does what you're after.

#include <stdio.h>

int main(int argc, char *argv[]) {

printf("My name is:");
fflush(stdout);
system("/bin/echo -n syntax_Error");
printf("I am 17 yrs old\n");
fflush(stdout);

}

$ cc     main.c   -o main
$ ./main
My name is:syntax_ErrorI am 17 yrs old

Rather than just use 'system' also look at 'execve' etc. 'man execve'

5
Blagovest Buyukliev On

You may need to explicitly flush the output buffer with fflush(stdout) after the first printf call. The system call spawns a new process which has its own buffering. Eventually this process terminates and flushes its buffer, but the parent process' buffer is totally unrelated.

It is worth noting that most libc implementations will flush automatically on every occurrence of a newline character, so an fflush call would be unnecessary if you had a newline character at the end of the first message.

2
T.E.D. On

If you wanted to use sync objects, you'd have to find some way to make that system call use them too. That would probably mean writing another program rather than using echo. Kinda messy.

Probably a smarter way to handle it would be to either use all the same method for your console output (all system calls or all printfs), or to pick one of them to output to a log file instead of the console.