2 * Generic implementation of background process infrastructure.
4 #include "sub-process.h"
8 int cmd2process_cmp(const struct subprocess_entry
*e1
,
9 const struct subprocess_entry
*e2
,
12 return strcmp(e1
->cmd
, e2
->cmd
);
15 struct subprocess_entry
*subprocess_find_entry(struct hashmap
*hashmap
, const char *cmd
)
17 struct subprocess_entry key
;
19 hashmap_entry_init(&key
, strhash(cmd
));
21 return hashmap_get(hashmap
, &key
, NULL
);
24 void subprocess_read_status(int fd
, struct strbuf
*status
)
29 line
= packet_read_line(fd
, NULL
);
32 pair
= strbuf_split_str(line
, '=', 2);
33 if (pair
[0] && pair
[0]->len
&& pair
[1]) {
34 /* the last "status=<foo>" line wins */
35 if (!strcmp(pair
[0]->buf
, "status=")) {
37 strbuf_addbuf(status
, pair
[1]);
40 strbuf_list_free(pair
);
44 void subprocess_stop(struct hashmap
*hashmap
, struct subprocess_entry
*entry
)
49 entry
->process
.clean_on_exit
= 0;
50 kill(entry
->process
.pid
, SIGTERM
);
51 finish_command(&entry
->process
);
53 hashmap_remove(hashmap
, entry
, NULL
);
56 static void subprocess_exit_handler(struct child_process
*process
)
58 sigchain_push(SIGPIPE
, SIG_IGN
);
59 /* Closing the pipe signals the subprocess to initiate a shutdown. */
62 sigchain_pop(SIGPIPE
);
63 /* Finish command will wait until the shutdown is complete. */
64 finish_command(process
);
67 int subprocess_start(struct hashmap
*hashmap
, struct subprocess_entry
*entry
, const char *cmd
,
68 subprocess_start_fn startfn
)
71 struct child_process
*process
;
72 const char *argv
[] = { cmd
, NULL
};
75 process
= &entry
->process
;
77 child_process_init(process
);
79 process
->use_shell
= 1;
82 process
->clean_on_exit
= 1;
83 process
->clean_on_exit_handler
= subprocess_exit_handler
;
85 err
= start_command(process
);
87 error("cannot fork to run subprocess '%s'", cmd
);
91 hashmap_entry_init(entry
, strhash(cmd
));
95 error("initialization for subprocess '%s' failed", cmd
);
96 subprocess_stop(hashmap
, entry
);
100 hashmap_add(hashmap
, entry
);