Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...