/
background.c
1913 lines (1667 loc) · 40.2 KB
/
background.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* vifm
* Copyright (C) 2001 Ken Steen.
* Copyright (C) 2011 xaizek.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "background.h"
#ifdef _WIN32
#include <windows.h>
#endif
#include <fcntl.h> /* open() */
#include <sys/stat.h> /* O_RDONLY */
#include <sys/types.h> /* pid_t ssize_t */
#ifndef _WIN32
#include <sys/wait.h> /* waitpid() */
#endif
#include <signal.h> /* SIG* kill() */
#include <unistd.h> /* execve() fork() setsid() usleep() */
#include <assert.h> /* assert() */
#include <errno.h> /* errno */
#include <stddef.h> /* NULL wchar_t */
#include <stdint.h> /* uintptr_t */
#include <stdlib.h> /* EXIT_FAILURE _Exit() free() malloc() */
#include <string.h> /* strdup() */
#include "cfg/config.h"
#include "compat/pthread.h"
#include "engine/var.h"
#include "engine/variables.h"
#include "modes/dialogs/msg_dialog.h"
#include "ui/cancellation.h"
#include "ui/statusline.h"
#include "ui/ui.h"
#include "utils/cancellation.h"
#include "utils/env.h"
#include "utils/event.h"
#include "utils/fs.h"
#include "utils/log.h"
#include "utils/path.h"
#include "utils/selector.h"
#include "utils/str.h"
#include "utils/utils.h"
#include "cmd_completion.h"
#include "status.h"
/**
* This unit implements three kinds of backgrounded operations:
* - external applications run from vifm (commands);
* - threads that perform auxiliary work (tasks), like counting size of
* directories;
* - threads that perform important work (operations), like file copying,
* deletion, etc.
*
* All jobs can be viewed via :jobs menu.
*
* Tasks and operations can provide progress information for displaying it in
* UI.
*
* Operations are displayed on designated job bar.
*
* On non-Windows systems background thread reads data from error streams of
* external applications, which are then displayed by main thread. This thread
* maintains its own list of jobs (via err_next field), which is added to by
* building a temporary list with new_err_jobs pointing to its head. Every job
* that has associated external process has the following life cycle:
* 1. Created by main thread and passed to error thread through new_err_jobs.
* 2. Either gets marked by signal handler or its stream reaches EOF.
* 3. Its use_count field is decremented.
* 4. Main thread frees corresponding entry.
*/
/* Turns pointer (P) to field (F) of a structure (S) to address of that
* structure. */
#define STRUCT_FROM_FIELD(S, F, P) ((S *)((char *)P - offsetof(S, F)))
/* Special value of process id for internal tasks running in background
* threads. */
#define WRONG_PID ((pid_t)-1)
/* Size of error message reading buffer. */
#define ERR_MSG_LEN 1025
/* Value of job communication mean for internal jobs. */
#ifndef _WIN32
#define NO_JOB_ID (-1)
#else
#define NO_JOB_ID INVALID_HANDLE_VALUE
#endif
/* Structure with passed to background_task_bootstrap() so it can perform
* correct initialization/cleanup. */
typedef struct
{
bg_task_func func; /* Function to execute in a background thread. */
void *args; /* Argument to pass. */
bg_job_t *job; /* Job identifier that corresponds to the task. */
}
background_task_args;
static void set_jobcount_var(int count);
static void job_check(bg_job_t *job);
static void job_free(bg_job_t *job);
static void * error_thread(void *p);
static void update_error_jobs(bg_job_t **jobs);
static void free_drained_jobs(bg_job_t **jobs);
static void import_error_jobs(bg_job_t **jobs);
static void make_ready_list(const bg_job_t *jobs, selector_t *selector);
#ifndef _WIN32
static void rip_children(void);
static void rip_child(pid_t pid, int status);
static void report_error_msg(const char title[], const char text[]);
#endif
static bg_job_t * launch_external(const char cmd[], BgJobFlags flags,
ShellRequester by);
#ifdef _WIN32
static int finish_startup_info(STARTUPINFOW *startup);
#endif
static void append_error_msg(bg_job_t *job, const char err_msg[]);
static void place_on_job_bar(bg_job_t *job);
static void get_off_job_bar(bg_job_t *job);
static bg_job_t * add_background_job(pid_t pid, const char cmd[],
uintptr_t err, uintptr_t data, BgJobType type, int with_bg_op);
static void * background_task_bootstrap(void *arg);
static int update_job_status(bg_job_t *job);
static void mark_job_finished(bg_job_t *job, int exit_code);
static void poke_error_thread(void);
static int bg_op_cancel(bg_op_t *bg_op);
bg_job_t *bg_jobs = NULL;
/* Event to wake up error thread from sleep for processing by
* poke_error_thread(). */
static event_t *error_thread_event;
/* Head of list of newly started jobs. */
static bg_job_t *new_err_jobs;
/* Mutex to protect new_err_jobs. */
static pthread_mutex_t new_err_jobs_lock = PTHREAD_MUTEX_INITIALIZER;
/* Conditional variable to signal availability of new jobs in new_err_jobs. */
static pthread_cond_t new_err_jobs_cond = PTHREAD_COND_INITIALIZER;
/* Thread-local storage for bg_job_t associated with active thread. */
static pthread_key_t current_job;
int
bg_init(void)
{
error_thread_event = event_alloc();
if(error_thread_event == NULL)
{
return 1;
}
/* Create thread-local storage before starting any background threads. */
if(pthread_key_create(¤t_job, NULL) != 0)
{
event_free(error_thread_event);
return 1;
}
pthread_t id;
if(pthread_create(&id, NULL, &error_thread, NULL) != 0)
{
pthread_key_delete(current_job);
event_free(error_thread_event);
return 1;
}
return 0;
}
void
bg_check(void)
{
static int checking;
if(checking)
{
/* This function is not re-entrant. */
return;
}
checking = 1;
#ifndef _WIN32
/*
* Rip children even if there are no jobs because it doesn't guarantee absence
* of zombies.
*
* Do not do this in nested calls because implementation relies on job list
* and won't be able to update job status if the list is not available leaving
* job instances around in a permanent "running" state.
*/
rip_children();
#endif
poke_error_thread();
int active_jobs = 0;
bg_job_t *head = bg_jobs;
bg_jobs = NULL;
bg_job_t *p = head;
bg_job_t *prev = NULL;
while(p != NULL)
{
job_check(p);
/* In case of lock failure, assume the job is active. */
int running = 1;
int can_remove = 0;
if(pthread_spin_lock(&p->status_lock) == 0)
{
running = p->running;
can_remove = (!running && p->use_count == 0);
(void)pthread_spin_unlock(&p->status_lock);
}
active_jobs += (running && p->in_menu);
if(!running)
{
if(p->on_job_bar)
{
get_off_job_bar(p);
}
if(p->exit_cb != NULL)
{
p->exit_cb(p, p->exit_cb_arg);
p->exit_cb = NULL;
}
}
/* Remove job if it is finished now. */
if(can_remove)
{
bg_job_t *j = p;
if(prev != NULL)
prev->next = p->next;
else
head = p->next;
p = p->next;
job_free(j);
}
else
{
prev = p;
p = p->next;
}
}
assert(bg_jobs == NULL && "Job list shouldn't be used by anyone.");
bg_jobs = head;
set_jobcount_var(active_jobs);
checking = 0;
}
/* Updates builtin variable that holds number of active jobs. Schedules UI
* redraw on change. */
static void
set_jobcount_var(int count)
{
int old_count = var_to_int(getvar("v:jobcount"));
if(count != old_count)
{
var_t var = var_from_int(count);
setvar("v:jobcount", var);
var_free(var);
stats_redraw_later();
}
}
/* Checks status of the job. Processes error stream or checks whether process
* is still running. */
static void
job_check(bg_job_t *job)
{
char *new_errors;
/* Display portions of errors from the job while there are any. */
do
{
new_errors = NULL;
if(pthread_spin_lock(&job->errors_lock) == 0)
{
new_errors = job->new_errors;
job->new_errors = NULL;
job->new_errors_len = 0U;
(void)pthread_spin_unlock(&job->errors_lock);
}
if(new_errors != NULL && !job->skip_errors)
{
job->skip_errors = prompt_error_msg("Background Process Error",
new_errors);
}
free(new_errors);
}
while(new_errors != NULL);
(void)update_job_status(job);
}
/* Frees resources allocated by the job as well as the bg_job_t structure
* itself. The job can be NULL. */
static void
job_free(bg_job_t *job)
{
if(job == NULL)
{
return;
}
pthread_spin_destroy(&job->errors_lock);
pthread_spin_destroy(&job->status_lock);
if(job->with_bg_op)
{
pthread_spin_destroy(&job->bg_op_lock);
}
#ifndef _WIN32
if(job->err_stream != NO_JOB_ID)
{
close(job->err_stream);
}
#else
if(job->err_stream != NO_JOB_ID)
{
CloseHandle(job->err_stream);
}
if(job->hprocess != NO_JOB_ID)
{
CloseHandle(job->hprocess);
}
if(job->hjob != NO_JOB_ID)
{
CloseHandle(job->hjob);
}
#endif
if(job->input != NULL)
{
fclose(job->input);
}
if(job->output != NULL)
{
fclose(job->output);
}
free(job->bg_op.descr);
free(job->cmd);
free(job->new_errors);
free(job->errors);
free(job);
}
int
bg_and_wait_for_errors(char cmd[], const struct cancellation_t *cancellation)
{
#ifndef _WIN32
pid_t pid;
int error_pipe[2];
int result = 0;
if(pipe(error_pipe) != 0)
{
report_error_msg("File pipe error", "Error creating pipe");
return -1;
}
if((pid = fork()) == -1)
{
return -1;
}
if(pid == 0)
{
run_from_fork(error_pipe, 1, 0, cmd, SHELL_BY_APP);
}
else
{
char buf[80*10];
char linebuf[80];
int nread = 0;
close(error_pipe[1]); /* Close write end of pipe. */
wait_for_data_from(pid, NULL, error_pipe[0], cancellation);
buf[0] = '\0';
while((nread = read(error_pipe[0], linebuf, sizeof(linebuf) - 1)) > 0)
{
const int read_empty_line = nread == 1 && linebuf[0] == '\n';
result = -1;
linebuf[nread] = '\0';
if(!read_empty_line)
{
strncat(buf, linebuf, sizeof(buf) - strlen(buf) - 1);
}
wait_for_data_from(pid, NULL, error_pipe[0], cancellation);
}
close(error_pipe[0]);
if(result != 0)
{
report_error_msg("Background Process Error", buf);
}
else
{
result = status_to_exit_code(get_proc_exit_status(pid, cancellation));
}
}
return result;
#else
return -1;
#endif
}
/* Entry point of a thread which reads input from input of active background
* programs. Does not return. */
static void *
error_thread(void *p)
{
enum { ERROR_SELECT_TIMEOUT_MS = 250 };
bg_job_t *jobs = NULL;
selector_t *selector = selector_alloc();
if(selector == NULL)
{
return NULL;
}
(void)pthread_detach(pthread_self());
block_all_thread_signals();
const event_end_t event_end = event_wait_end(error_thread_event);
while(1)
{
update_error_jobs(&jobs);
make_ready_list(jobs, selector);
selector_add(selector, event_end);
while(selector_wait(selector, ERROR_SELECT_TIMEOUT_MS))
{
int need_update_list = (jobs == NULL);
if(selector_is_ready(selector, event_end))
{
(void)event_reset(error_thread_event);
}
bg_job_t **job = &jobs;
while(*job != NULL)
{
bg_job_t *const j = *job;
char err_msg[ERR_MSG_LEN];
ssize_t nread;
if(j->drained)
{
/* List update drops jobs which aren't running anymore thus allowing
* them to be gone. Matters at least in tests which wait for all
* tasks to finish and looping here leads to a timeout. */
need_update_list = 1;
goto next_job;
}
if(!selector_is_ready(selector, j->err_stream))
{
goto next_job;
}
#ifndef _WIN32
nread = read(j->err_stream, err_msg, sizeof(err_msg) - 1U);
#else
nread = -1;
DWORD bytes_read;
if(ReadFile(j->err_stream, err_msg, sizeof(err_msg) - 1U, &bytes_read,
NULL))
{
nread = bytes_read;
}
#endif
if(nread > 0)
{
err_msg[nread] = '\0';
append_error_msg(j, err_msg);
}
else
{
/* EOF or some error. */
need_update_list = 1;
j->drained = 1;
}
next_job:
job = &j->err_next;
}
if(!need_update_list && pthread_mutex_lock(&new_err_jobs_lock) == 0)
{
need_update_list = (new_err_jobs != NULL);
(void)pthread_mutex_unlock(&new_err_jobs_lock);
}
if(need_update_list)
{
break;
}
}
}
selector_free(selector);
event_free(error_thread_event);
return NULL;
}
/* Updates *jobs by removing finished tasks and adding new ones. */
static void
update_error_jobs(bg_job_t **jobs)
{
free_drained_jobs(jobs);
import_error_jobs(jobs);
}
/* Updates *jobs by removing finished tasks. */
static void
free_drained_jobs(bg_job_t **jobs)
{
bg_job_t **job = jobs;
while(*job != NULL)
{
bg_job_t *const j = *job;
if(j->drained && pthread_spin_lock(&j->status_lock) == 0)
{
/* Drop it from the list even if the job is still running, we won't be
* able to get anything out of it anyway. */
--j->use_count;
j->erroring = 0;
*job = j->err_next;
(void)pthread_spin_unlock(&j->status_lock);
continue;
}
job = &j->err_next;
}
}
/* Updates *jobs by adding new tasks. */
static void
import_error_jobs(bg_job_t **jobs)
{
bg_job_t *new_jobs;
/* Add new tasks to internal list, wait if there are no jobs. */
if(pthread_mutex_lock(&new_err_jobs_lock) != 0)
{
return;
}
while(*jobs == NULL && new_err_jobs == NULL)
{
if(pthread_cond_wait(&new_err_jobs_cond, &new_err_jobs_lock) != 0)
{
break;
}
}
new_jobs = new_err_jobs;
new_err_jobs = NULL;
(void)pthread_mutex_unlock(&new_err_jobs_lock);
/* Prepend new jobs to the list. */
while(new_jobs != NULL)
{
bg_job_t *const new_job = new_jobs;
new_jobs = new_jobs->err_next;
assert(new_job->type == BJT_COMMAND &&
"Only external commands should be here.");
/* Mark a this job as an interesting one to avoid it being killed until we
* have a chance to read error stream. */
new_job->drained = 0;
new_job->err_next = *jobs;
*jobs = new_job;
}
}
/* Reinitializes the selector with up-to-date list of objects to watch. */
static void
make_ready_list(const bg_job_t *jobs, selector_t *selector)
{
selector_reset(selector);
while(jobs != NULL)
{
selector_add(selector, jobs->err_stream);
jobs = jobs->err_next;
}
}
#ifndef _WIN32
/* Rips children updating status of jobs in the process. */
static void
rip_children(void)
{
int status;
pid_t pid;
/* This needs to be a loop in case of multiple blocked signals. */
while((pid = waitpid(-1, &status, WNOHANG)) > 0)
{
if(WIFEXITED(status) || WIFSIGNALED(status))
{
rip_child(pid, status);
}
}
}
/* Looks up a child in job list and rips it if found. */
static void
rip_child(pid_t pid, int status)
{
bg_job_t *job;
for(job = bg_jobs; job != NULL; job = job->next)
{
if(job->pid == pid)
{
mark_job_finished(job, status_to_exit_code(status));
break;
}
}
}
/* Either displays error message to the user for foreground operations or saves
* it for displaying on the next invocation of bg_check(). */
static void
report_error_msg(const char title[], const char text[])
{
bg_job_t *const job = pthread_getspecific(current_job);
if(job == NULL)
{
ui_cancellation_push_off();
show_error_msg(title, text);
ui_cancellation_pop();
}
else
{
append_error_msg(job, text);
}
}
#endif
/* Appends message to error-related fields of the job. */
static void
append_error_msg(bg_job_t *job, const char err_msg[])
{
if(err_msg[0] != '\0' && pthread_spin_lock(&job->errors_lock) == 0)
{
(void)strappend(&job->errors, &job->errors_len, err_msg);
(void)strappend(&job->new_errors, &job->new_errors_len, err_msg);
(void)pthread_spin_unlock(&job->errors_lock);
}
}
#ifndef _WIN32
pid_t
bg_run_and_capture(char cmd[], int user_sh, FILE *in, FILE **out, FILE **err)
{
pid_t pid;
int out_pipe[2];
int error_pipe[2];
if(out != NULL && pipe(out_pipe) != 0)
{
show_error_msg("File pipe error", "Error creating pipe");
return (pid_t)-1;
}
if(err != NULL && pipe(error_pipe) != 0)
{
show_error_msg("File pipe error", "Error creating pipe");
if(out != NULL)
{
close(out_pipe[0]);
close(out_pipe[1]);
}
return (pid_t)-1;
}
if(in != NULL)
{
fflush(in);
}
if((pid = fork()) == -1)
{
if(out != NULL)
{
close(out_pipe[0]);
close(out_pipe[1]);
}
if(err != NULL)
{
close(error_pipe[0]);
close(error_pipe[1]);
}
return (pid_t)-1;
}
if(pid == 0)
{
if(out != NULL)
{
bind_pipe_or_die(STDOUT_FILENO, out_pipe[1], out_pipe[0]);
}
if(err != NULL)
{
bind_pipe_or_die(STDERR_FILENO, error_pipe[1], error_pipe[0]);
}
if(in != NULL)
{
rewind(in);
if(dup2(fileno(in), STDIN_FILENO) == -1)
{
_Exit(EXIT_FAILURE);
}
fclose(in);
}
char *sh_flag = user_sh ? cfg.shell_cmd_flag : "-c";
prepare_for_exec();
execvp(get_execv_path(cfg.shell),
make_execv_array(cfg.shell, sh_flag, cmd));
_Exit(127);
}
if(out != NULL)
{
close(out_pipe[1]);
*out = fdopen(out_pipe[0], "r");
}
if(err != NULL)
{
close(error_pipe[1]);
*err = fdopen(error_pipe[0], "r");
}
return pid;
}
#else
/* Runs command in a background and redirects its stdout and stderr streams to
* file streams which are set. Input and output are redirected only if the
* corresponding parameter isn't NULL. Don't pass pipe for input, it can cause
* deadlock. Returns (pid_t)0 or (pid_t)-1 on error. */
static pid_t
background_and_capture_internal(char cmd[], int user_sh, FILE *in, FILE **out,
FILE **err, int out_pipe[2], int err_pipe[2])
{
const wchar_t *args[4];
char *cwd;
int code;
wchar_t *final_wide_cmd;
wchar_t *wide_sh = NULL;
wchar_t *wide_sh_flag;
const int use_cmd = (!user_sh || curr_stats.shell_type == ST_CMD);
if(in != NULL)
{
fflush(in);
rewind(in);
if(_dup2(_fileno(in), _fileno(stdin)) != 0)
return (pid_t)-1;
}
if(out != NULL && _dup2(out_pipe[1], _fileno(stdout)) != 0)
return (pid_t)-1;
if(err != NULL && _dup2(err_pipe[1], _fileno(stderr)) != 0)
return (pid_t)-1;
/* At least cmd.exe is incapable of handling UNC paths. */
cwd = save_cwd();
if(cwd != NULL && is_unc_path(cwd))
{
(void)chdir(get_tmpdir());
}
wide_sh = to_wide(use_cmd ? "cmd" : cfg.shell);
wide_sh_flag = to_wide(user_sh ? cfg.shell_cmd_flag : "/C");
if(use_cmd)
{
final_wide_cmd = to_wide(cmd);
args[0] = wide_sh;
args[1] = wide_sh_flag;
args[2] = final_wide_cmd;
args[3] = NULL;
}
else
{
/* Nobody cares that there is an array of arguments, all arguments just get
* concatenated anyway... Therefore we need to take care of escaping stuff
* ourselves. */
char *const modified_cmd = win_make_sh_cmd(cmd,
user_sh ? SHELL_BY_USER : SHELL_BY_APP);
final_wide_cmd = to_wide(modified_cmd);
free(modified_cmd);
args[0] = final_wide_cmd;
args[1] = NULL;
}
code = _wspawnvp(P_NOWAIT, wide_sh, args);
free(wide_sh_flag);
free(wide_sh);
free(final_wide_cmd);
restore_cwd(cwd);
if(code == 0)
{
return (pid_t)-1;
}
if(out != NULL && (*out = _fdopen(out_pipe[0], "r")) == NULL)
{
return (pid_t)-1;
}
if(err != NULL && (*err = _fdopen(err_pipe[0], "r")) == NULL)
{
if(out != NULL)
{
fclose(*out);
}
return (pid_t)-1;
}
return 0;
}
pid_t
bg_run_and_capture(char cmd[], int user_sh, FILE *in, FILE **out, FILE **err)
{
int in_fd;
int out_fd, out_pipe[2];
int err_fd, err_pipe[2];
pid_t pid;
if(out != NULL && _pipe(out_pipe, 512, O_NOINHERIT) != 0)
{
show_error_msg("File pipe error", "Error creating pipe");
return (pid_t)-1;
}
if(err != NULL && _pipe(err_pipe, 512, O_NOINHERIT) != 0)
{
show_error_msg("File pipe error", "Error creating pipe");
if(out != NULL)
{
close(out_pipe[0]);
close(out_pipe[1]);
}
return (pid_t)-1;
}
in_fd = dup(_fileno(stdin));
out_fd = dup(_fileno(stdout));
err_fd = dup(_fileno(stderr));
pid = background_and_capture_internal(cmd, user_sh, in, out, err, out_pipe,
err_pipe);
if(out != NULL)
{
_close(out_pipe[1]);
}
if(err != NULL)
{
_close(err_pipe[1]);
}
_dup2(in_fd, _fileno(stdin));
_dup2(out_fd, _fileno(stdout));
_dup2(err_fd, _fileno(stderr));
if(pid == (pid_t)-1)
{
if(out != NULL)
{
_close(out_pipe[0]);
}
if(err != NULL)
{
_close(err_pipe[0]);
}
}
return pid;
}
#endif
int
bg_run_external(const char cmd[], int skip_errors, ShellRequester by,
FILE **input)
{
char *command = (cfg.fast_run ? fast_run_complete(cmd) : strdup(cmd));
if(command == NULL)
{
return 1;
}
const BgJobFlags flags = (input == NULL ? BJF_NONE : BJF_SUPPLY_INPUT);
bg_job_t *job = launch_external(command, flags, by);
free(command);
if(job == NULL)
{
if(input != NULL)
{
*input = NULL;
}
return 1;
}
if(input != NULL)
{
*input = job->input;
job->input = NULL;
}
/* It's safe to do this here because bg_check() is executed on the same
* thread as this function. */
job->skip_errors = skip_errors;
return 0;
}
bg_job_t *
bg_run_external_job(const char cmd[], BgJobFlags flags, const char descr[])
{
bg_job_t *job = launch_external(cmd, flags, SHELL_BY_APP);
if(job == NULL)
{
return NULL;
}
/* It's safe to do this here because bg_check() is executed on the same
* thread as this function. */
bg_job_incref(job);
job->skip_errors = 1;
if(flags & BJF_JOB_BAR_VISIBLE)
{
/* Set description before placing the job on the bar so that the first
* redraw will already have the description. */
bg_op_set_descr(&job->bg_op, descr);
place_on_job_bar(job);
}
job->in_menu = (flags & BJF_MENU_VISIBLE);
return job;
}
/* Starts a new external command job. Returns the new job or NULL on error. */
static bg_job_t *
launch_external(const char cmd[], BgJobFlags flags, ShellRequester by)
{