I am using jsonrpc-c to write a remote shell toy.
The client side uses nc
to send request to server:
echo "{\"method\":\"sayHello\"}" | nc localhost 1234
The code of the server is simple:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include "jsonrpc-c.h"
#define DEFAULT_PORT 1234 //the port users will be connecting to
static struct jrpc_server my_server;
cJSON * hello(jrpc_context * ctx, cJSON * params, cJSON *id) {
pid_t pid = fork();
if (pid==0)
{
freopen( "/dev/null", "w", stdout );
freopen( "/dev/null", "r", stdin );
signal(SIGCHLD,SIG_IGN);
while(true){
printf("hello in child\n");
}
exit(1);
}
printf("hello in father\n");
return cJSON_CreateString("done");
}
void main(int argc, char **argv)
{
int port;
if (argc == 2)
port = atoi(argv[1]);
else
port = DEFAULT_PORT;
jrpc_server_init(&my_server, (int)port);
jrpc_register_procedure(&my_server, hello, "sayHello", NULL);
jrpc_server_run(&my_server);
jrpc_server_destroy(&my_server);
}
When executing echo "{\"method\":\"sayHello\"}" | nc localhost 1234
, the client blocks forever.
Are there any methods to let the client exit when the server's parent process returns, while allowing the server's child process to continue running?