0

I am trying to run a program that essentially runs forever. I need to start it with certain parameters that I load in so I am running it from within my c++ program. Say this is the program.

int main() {
   while(true) {
     // do something
   }
}

It compiles to a shared library object: forever.so.

If I do the following from c++ nothing happens.

int main() {
  system("forever.so &");
}

If I do the following my program blocks forever (as would be expected).

int main() {
  system("forever.so");
}

What am I doing wrong here?

I can provide the strace and other info.

To be clear. The issue is that if I check processes with

ps -a 

I do not see any of my processes. This is when the program is paused during a debug session so the processes should still be alive.

Keiros
  • 69
  • 1
  • 9

1 Answers1

3

system uses /bin/sh, which is a POSIX shell. & after a command means to run it in the background, which means it won't block. Read here for more info.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • I know that but the process itself doesn't show up in my list of processes when I run ps -a. – Keiros Nov 14 '20 at 18:20
  • 2
    Your program will exit (since it doesn't block) and send a HUP signal to the child, killing it. – Aplet123 Nov 14 '20 at 18:20
  • Okay great. I was not sure if I was doing something wrong but that makes sense. – Keiros Nov 14 '20 at 18:21
  • "since it doesn't block" is this refering to `while(0)` ? meanwhile questions says `while(true)` – 463035818_is_not_an_ai Nov 14 '20 at 18:22
  • The program should be blocking I was just trying to make it not blocking by running it in the background. – Keiros Nov 14 '20 at 18:24
  • If you want to run it in the background then you should either use c++'s [`std::thread`](https://en.cppreference.com/w/cpp/thread/thread) or c's [fork and exec](https://stackoverflow.com/questions/19099663/how-to-correctly-use-fork-exec-wait) instead of hacking it with `system`. – Aplet123 Nov 14 '20 at 18:28
  • @idclev463035818: I'm a linux novice, but I think it's: The terminal he's in is a program (process#1), from that he runs his second code (process#2), which launches his first code (process#3), and then #2 does not block. Since #2 is now done, it exits, which kills it's child of process#3. – Mooing Duck Nov 14 '20 at 18:44
  • @MooingDuck thanks that makes sense. I already suspected that the comment did not refer to `while(0)` but wasn't sure – 463035818_is_not_an_ai Nov 14 '20 at 18:45