Add run_command_v_opt_cd: chdir into a directory before exec
It can make code simplier (no need to preserve cwd) and safer (no chance the cwd of the current process is accidentally forgotten). Signed-off-by: Alex Riesen <raa.lkml@gmail.com> Signed-off-by: Junio C Hamano <junkio@cox.net>
Alex Riesen committed
May 22, 2007 at 23:48 UTC
1568fea01eb25a293f8dae570a31ca34d41b5442
2 files changed
+24
-5
run-command.c
+22
-5
@@ -73,6 +73,9 @@ int start_command(struct child_process *cmd)
73
close(cmd->out);
74
}
75
76
+ if (cmd->dir && chdir(cmd->dir))
77
+ die("exec %s: cd to %s failed (%s)", cmd->argv[0],
78
+ cmd->dir, strerror(errno));
79
if (cmd->git_cmd) {
80
execv_git_cmd(cmd->argv);
81
} else {
@@ -133,13 +136,27 @@ int run_command(struct child_process *cmd)
136
return finish_command(cmd);
137
}
138
139
+static void prepare_run_command_v_opt(struct child_process *cmd,
140
+ const char **argv, int opt)
141
+{
142
+ memset(cmd, 0, sizeof(*cmd));
143
+ cmd->argv = argv;
144
+ cmd->no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
145
+ cmd->git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
146
+ cmd->stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
147
+}
148
+
149
int run_command_v_opt(const char **argv, int opt)
150
{
151
struct child_process cmd;
139
- memset(&cmd, 0, sizeof(cmd));
140
- cmd.argv = argv;
141
- cmd.no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
142
- cmd.git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
143
- cmd.stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
152
+ prepare_run_command_v_opt(&cmd, argv, opt);
153
+ return run_command(&cmd);
154
+}
155
+
156
+int run_command_v_opt_cd(const char **argv, int opt, const char *dir)
157
+{
158
+ struct child_process cmd;
159
+ prepare_run_command_v_opt(&cmd, argv, opt);
160
+ cmd.dir = dir;
161
return run_command(&cmd);
162
}
run-command.h
+2
@@ -16,6 +16,7 @@ struct child_process {
16
pid_t pid;
17
int in;
18
int out;
19
+ const char *dir;
20
unsigned close_in:1;
21
unsigned close_out:1;
22
unsigned no_stdin:1;
@@ -32,5 +33,6 @@ int run_command(struct child_process *);
33
#define RUN_GIT_CMD 2 /*If this is to be git sub-command */
34
#define RUN_COMMAND_STDOUT_TO_STDERR 4
35
int run_command_v_opt(const char **argv, int opt);
36
+int run_command_v_opt_cd(const char **argv, int opt, const char *dir);
37
38
#endif