简体   繁体   中英

How to automatically stop a program.c and input a command in Linux?

So i have this program that is supposed to be a (super basic) server in Linux that shows me this menu:

What u want to do?
 0 -> Exit
 1 -> Add product
 2 -> Show products list
 3 -> Turn on server

And i want it so that when you put the number 3, the server.c stops, like when you press CTRL + Z and send the commnad "bg" so that the server runs in backgroundg (like when you do the command "./server&") so i can open the client.c and interact with the server.

Example of what i want it to do when you input 3 (on here i did it manually on the propmt):

estgv18708@viriato:~/tp6$ ./server

What u want to do?
 0 -> Exit
 1 -> Add product
 2 -> Show products list
 3 -> Turn on server
3

^Z
[1]+  Stopped                 ./server
estgv18708@viriato:~/tp6$ bg
[1]+ ./servidor &

Thanks in advance: :D

Probably an XY-problem here -- why would you want to do this?

The basic issue is that this presupposes your server program is run from a shell and you want to return to the shell to do stuff. But what is the server going to be doing in the meantime? The shell will have (need) control of the input and output so the server pretty much just needs to wait.

You can get the same effect as ^z by calling kill:

kill(getpid(), SIGSTOP);

will have the server send a STOP signal to itself. The shell (which is monitoring progress of the program), will notice this and print the "Stopped" message and then prompt for what to do. The server will be stopped, and you can resume it with the shell's fg command (or put it into the background with bg ). However, if your server program is not run from a shell (it is just running directly in a terminal), this will simply stop the server and nothing else will happen.

More commonly what you want to do here is run a subshell:

system(getenv("SHELL"));

which will start a new shell and will wait for it to complete. When the shell exits (use the exit command or type ^d at the shell prompt) the server will resume.

If you want the server to continue to run while the shell runs, you can use fork+exec to run the shell in the child and continue running the server in the parent, but you need to be careful about using the terminal input and output (the server and shell will be fighting for it).

Cant u just do system("bg"); ? U dond need to stop the program just need to put it on the background

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM