doc: describe git svn init --ignore-refs
[git/git-svn.git] / sub-process.c
blob92f8aea70aa0bc7654b89bebc3e72b197953e84a
1 /*
2 * Generic implementation of background process infrastructure.
3 */
4 #include "sub-process.h"
5 #include "sigchain.h"
6 #include "pkt-line.h"
8 int cmd2process_cmp(const struct subprocess_entry *e1,
9 const struct subprocess_entry *e2,
10 const void *unused)
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));
20 key.cmd = cmd;
21 return hashmap_get(hashmap, &key, NULL);
24 int subprocess_read_status(int fd, struct strbuf *status)
26 struct strbuf **pair;
27 char *line;
28 int len;
30 for (;;) {
31 len = packet_read_line_gently(fd, NULL, &line);
32 if ((len < 0) || !line)
33 break;
34 pair = strbuf_split_str(line, '=', 2);
35 if (pair[0] && pair[0]->len && pair[1]) {
36 /* the last "status=<foo>" line wins */
37 if (!strcmp(pair[0]->buf, "status=")) {
38 strbuf_reset(status);
39 strbuf_addbuf(status, pair[1]);
42 strbuf_list_free(pair);
45 return (len < 0) ? len : 0;
48 void subprocess_stop(struct hashmap *hashmap, struct subprocess_entry *entry)
50 if (!entry)
51 return;
53 entry->process.clean_on_exit = 0;
54 kill(entry->process.pid, SIGTERM);
55 finish_command(&entry->process);
57 hashmap_remove(hashmap, entry, NULL);
60 static void subprocess_exit_handler(struct child_process *process)
62 sigchain_push(SIGPIPE, SIG_IGN);
63 /* Closing the pipe signals the subprocess to initiate a shutdown. */
64 close(process->in);
65 close(process->out);
66 sigchain_pop(SIGPIPE);
67 /* Finish command will wait until the shutdown is complete. */
68 finish_command(process);
71 int subprocess_start(struct hashmap *hashmap, struct subprocess_entry *entry, const char *cmd,
72 subprocess_start_fn startfn)
74 int err;
75 struct child_process *process;
76 const char *argv[] = { cmd, NULL };
78 entry->cmd = cmd;
79 process = &entry->process;
81 child_process_init(process);
82 process->argv = argv;
83 process->use_shell = 1;
84 process->in = -1;
85 process->out = -1;
86 process->clean_on_exit = 1;
87 process->clean_on_exit_handler = subprocess_exit_handler;
89 err = start_command(process);
90 if (err) {
91 error("cannot fork to run subprocess '%s'", cmd);
92 return err;
95 hashmap_entry_init(entry, strhash(cmd));
97 err = startfn(entry);
98 if (err) {
99 error("initialization for subprocess '%s' failed", cmd);
100 subprocess_stop(hashmap, entry);
101 return err;
104 hashmap_add(hashmap, entry);
105 return 0;