Ahmed Jolani
Ahmed Jolani

Reputation: 3072

close() after system() weird behavior

I'm calling system("bash ../tools/bashScript \"This is an argument!\" &"), then I'm calling close(socketFD) directly after system returns, of course I've read that system's argument appended with a & will fork the command, so system returns immediately and I've checked that!

Now the problem is that I don't want the socket to stay connected while the command is being executed, but the weirdest thing is that the work flow of the program continues and close is somewhat seen and overlooked and once the command finishes the close takes effect!

I tried to call close twice after each others to make sure to delete every copy of the socketFD if created, still the same problem, I honestly don't know why close is being called but doesn't take effect until the command (the bash script) finishes!

Please advise!

Upvotes: 2

Views: 56

Answers (1)

Gian
Gian

Reputation: 13955

I'm a little confused about what you're doing, but system is effectively a thin wrapper over fork. This means that both processes have copies* of the socket descriptor, and only one "copy" is closed. The other persists until the forked process in which the system command is executing terminates as well.

Why not just close the socket before you call system?

You could also try using shutdown on the dup'd descriptors, e.g.:

shutdown(s,SHUT_RDWR);

*Tthe rules around what happens to file and socket descriptors through fork calls is a little more subtle than "copying", but this is sufficient to explain why it's not working for you.

Upvotes: 2

Related Questions