0

I am writing a c++ code in my project that should tell whether my websphere mq server is running or not. In order to extract that we need to run "/opt/mqm/bin/amq status" to show whether it is running or not.Tricky thing is MQHOME=/opt/mqm is not constant across unix platforms.So,We agreed to a design to extract the MQHOME path from the absolute path of the process "amqzlaar0" which is an mq server process.So, we need to issue the below command that shows the process "amqzlaar0" along with its fullpath.Then,we will store the string in an array to extract MQHOME.

"ps -ef | grep amqzlaar0 | awk '{print $(NF-1)}' " 

system() function is failing with exit code -1 when i use pipe symbol "|". But, if I issue just system("ps -ef"),it works.

Please help me on how to execute a pipe seperated command using system.

Your help is much appreciated. Regards, Sriram

  • 1
    Piping functionality is provided by a shell, so it's not part of any single system command. I have very little experience with piping in C/C++ code but when I did it I manually set up pipes (file descriptors) for the communication. – keyser Aug 12 '14 at 18:52
  • Write a helper script containing your bash commands and then just run the helper script via system() or popen(). – Paul R Aug 12 '14 at 19:16
  • 1
    What system? Posix requires `system` to pass the command through a shell, so the pipes _should_ work (and I've used similar commands from time to time with no problems). – James Kanze Aug 12 '14 at 19:29
  • 2
    You can shorten the `ps` some to: `ps -ef | awk '/[a]mqzlaar0/ {print $(NF-1)}'` Putting the `a` in brackets makes you not get the grep itself. – Jotne Aug 12 '14 at 21:54
  • As Jotne points out, there's never a need to pipe the output of grep to awk, but in this case awk is unnecessary since you can control what ps outputs. Try `ps -e -o command` – William Pursell Aug 13 '14 at 12:53

2 Answers2

2

I believe you should not run a command to check that amqzlaar0 is running, but query the proc(5) filesystem (on Linux).

Notice that /proc/ is not portable (e.g. not standardized in Posix). Some Unixes don't have it, and Solaris and Linux have very different /proc/ file systems.

If really want to run a command, use e.g. snprintf(3) to build the command (or std::string or std::ostringstream) then use popen(3) (and pclose) to run the command

Read Advanced Linux Programming to get a better view of Linux Programming. See also syscalls(2)

BTW, some people might have aliased e.g. grep (perhaps in their .bashrc), so you probably should put full paths in your command (so /bin/grep not grep etc...).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

Just run ps -Ef. You're a C++ programmer. The equivalent of grep and awk is not hard in C++, and it's faster in C++ (doesn't require two additional processes)

MSalters
  • 173,980
  • 10
  • 155
  • 350