1

I want to know how can I do something like this in a C program.

if wget -q www.someurl.com;
then echo OK;
else echo Not there;
fi
  • Your shell snippet is hosed, you are capturing the output of `wget` in `r`, not the exit code. Anyway, the proper idiom is `if wget -q www.someurl.com; then echo OK; else echo Not there; fi` – tripleee Dec 22 '14 at 04:14
  • I don't know how it is done in the shell but what I want to know is how it is done in a function in the C programming language. –  Dec 22 '14 at 09:05
  • Clearly people were able to guess what you really meant but seriously, if you post code to show what you want, you should either indicate what the problem with the code is or make sure it does what you want. – tripleee Dec 22 '14 at 09:06

2 Answers2

4
  1. From the parent do fork().
  2. Inside the child created by 1. do exec*().
  3. From the parent or a signal handler listening to SIGCHLD do wait(&status).
  4. Finally use WEXITSTATUS(status) to get the equivalent to r=$? from your script.
alk
  • 69,737
  • 10
  • 105
  • 255
  • Or use system(). You'll still need to use WEXITSTATUS to separate the return code from the signal information. – Russell Reed Dec 21 '14 at 15:53
  • 1
    Using `system()` is highly unportable as one never knows which shell might get involved. @RussellReed – alk Dec 21 '14 at 17:11
2

I'd rather not do this through exec but through leveraging something like libcurl http://curl.haxx.se/libcurl/c/

Hans Z.
  • 50,496
  • 12
  • 102
  • 115