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 int subprocess_read_status(int fd
, struct strbuf
*status
)
31 len
= packet_read_line_gently(fd
, NULL
, &line
);
32 if ((len
< 0) || !line
)
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=")) {
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
)
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. */
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
)
75 struct child_process
*process
;
76 const char *argv
[] = { cmd
, NULL
};
79 process
= &entry
->process
;
81 child_process_init(process
);
83 process
->use_shell
= 1;
86 process
->clean_on_exit
= 1;
87 process
->clean_on_exit_handler
= subprocess_exit_handler
;
89 err
= start_command(process
);
91 error("cannot fork to run subprocess '%s'", cmd
);
95 hashmap_entry_init(entry
, strhash(cmd
));
99 error("initialization for subprocess '%s' failed", cmd
);
100 subprocess_stop(hashmap
, entry
);
104 hashmap_add(hashmap
, entry
);