comparison src/process-unix.c @ 428:3ecd8885ac67 r21-2-22

Import from CVS: tag r21-2-22
author cvs
date Mon, 13 Aug 2007 11:28:15 +0200
parents
children 8de8e3f6228a
comparison
equal deleted inserted replaced
427:0a0253eac470 428:3ecd8885ac67
1 /* Asynchronous subprocess implementation for UNIX
2 Copyright (C) 1985, 1986, 1987, 1988, 1992, 1993, 1994, 1995
3 Free Software Foundation, Inc.
4 Copyright (C) 1995 Sun Microsystems, Inc.
5 Copyright (C) 1995, 1996 Ben Wing.
6
7 This file is part of XEmacs.
8
9 XEmacs is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
13
14 XEmacs is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with XEmacs; see the file COPYING. If not, write to
21 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 Boston, MA 02111-1307, USA. */
23
24 /* This file has been Mule-ized except for `start-process-internal',
25 `open-network-stream-internal' and `open-multicast-group-internal'. */
26
27 /* This file has been split into process.c and process-unix.c by
28 Kirill M. Katsnelson <kkm@kis.ru>, so please bash him and not
29 the original author(s) */
30
31 #include <config.h>
32
33 #if !defined (NO_SUBPROCESSES)
34
35 /* The entire file is within this conditional */
36
37 #include "lisp.h"
38
39 #include "buffer.h"
40 #include "events.h"
41 #include "frame.h"
42 #include "hash.h"
43 #include "lstream.h"
44 #include "opaque.h"
45 #include "process.h"
46 #include "procimpl.h"
47 #include "sysdep.h"
48 #include "window.h"
49 #ifdef FILE_CODING
50 #include "file-coding.h"
51 #endif
52
53 #include <setjmp.h>
54 #include "sysfile.h"
55 #include "sysproc.h"
56 #include "systime.h"
57 #include "syssignal.h" /* Always include before systty.h */
58 #include "systty.h"
59 #include "syswait.h"
60
61
62 /*
63 * Implementation-specific data. Pointed to by Lisp_Process->process_data
64 */
65
66 struct unix_process_data
67 {
68 /* Non-0 if this is really a ToolTalk channel. */
69 int connected_via_filedesc_p;
70 /* Descriptor by which we read from this process. -1 for dead process */
71 int infd;
72 /* Descriptor for the tty which this process is using.
73 -1 if we didn't record it (on some systems, there's no need). */
74 int subtty;
75 /* Name of subprocess terminal. */
76 Lisp_Object tty_name;
77 /* Non-false if communicating through a pty. */
78 char pty_flag;
79 };
80
81 #define UNIX_DATA(p) ((struct unix_process_data*)((p)->process_data))
82
83 #ifdef HAVE_PTYS
84 /* The file name of the pty opened by allocate_pty. */
85
86 static char pty_name[24];
87 #endif
88
89
90
91 /**********************************************************************/
92 /* Static helper routines */
93 /**********************************************************************/
94
95 static SIGTYPE
96 close_safely_handler (int signo)
97 {
98 EMACS_REESTABLISH_SIGNAL (signo, close_safely_handler);
99 SIGRETURN;
100 }
101
102 static void
103 close_safely (int fd)
104 {
105 stop_interrupts ();
106 signal (SIGALRM, close_safely_handler);
107 alarm (1);
108 close (fd);
109 alarm (0);
110 start_interrupts ();
111 }
112
113 static void
114 close_descriptor_pair (int in, int out)
115 {
116 if (in >= 0)
117 close (in);
118 if (out != in && out >= 0)
119 close (out);
120 }
121
122 /* Close all descriptors currently in use for communication
123 with subprocess. This is used in a newly-forked subprocess
124 to get rid of irrelevant descriptors. */
125
126 static int
127 close_process_descs_mapfun (CONST void* key, void* contents, void* arg)
128 {
129 Lisp_Object proc;
130 CVOID_TO_LISP (proc, contents);
131 event_stream_delete_stream_pair (XPROCESS(proc)->pipe_instream,
132 XPROCESS(proc)->pipe_outstream);
133 return 0;
134 }
135
136 /* #### This function is currently called from child_setup
137 in callproc.c. It should become static though - kkm */
138 void
139 close_process_descs (void)
140 {
141 maphash (close_process_descs_mapfun, usid_to_process, 0);
142 }
143
144 /* connect to an existing file descriptor. This is very similar to
145 open-network-stream except that it assumes that the connection has
146 already been initialized. It is currently used for ToolTalk
147 communication. */
148
149 /* This function used to be visible on the Lisp level, but there is no
150 real point in doing that. Here is the doc string:
151
152 "Connect to an existing file descriptor.\n\
153 Returns a subprocess-object to represent the connection.\n\
154 Input and output work as for subprocesses; `delete-process' closes it.\n\
155 Args are NAME BUFFER INFD OUTFD.\n\
156 NAME is name for process. It is modified if necessary to make it unique.\n\
157 BUFFER is the buffer (or buffer-name) to associate with the process.\n\
158 Process output goes at end of that buffer, unless you specify\n\
159 an output stream or filter function to handle the output.\n\
160 BUFFER may be also nil, meaning that this process is not associated\n\
161 with any buffer\n\
162 INFD and OUTFD specify the file descriptors to use for input and\n\
163 output, respectively."
164 */
165
166 Lisp_Object
167 connect_to_file_descriptor (Lisp_Object name, Lisp_Object buffer,
168 Lisp_Object infd, Lisp_Object outfd)
169 {
170 /* This function can GC */
171 Lisp_Object proc;
172 int inch;
173
174 CHECK_STRING (name);
175 CHECK_INT (infd);
176 CHECK_INT (outfd);
177
178 inch = XINT (infd);
179 if (get_process_from_usid (FD_TO_USID(inch)))
180 error ("There is already a process connected to fd %d", inch);
181 if (!NILP (buffer))
182 buffer = Fget_buffer_create (buffer);
183 proc = make_process_internal (name);
184
185 XPROCESS (proc)->pid = Fcons (infd, name);
186 XPROCESS (proc)->buffer = buffer;
187 init_process_io_handles (XPROCESS (proc), (void*)inch, (void*)XINT (outfd), 0);
188 UNIX_DATA (XPROCESS (proc))->connected_via_filedesc_p = 1;
189
190 event_stream_select_process (XPROCESS (proc));
191
192 return proc;
193 }
194
195 #ifdef HAVE_PTYS
196
197 /* Open an available pty, returning a file descriptor.
198 Return -1 on failure.
199 The file name of the terminal corresponding to the pty
200 is left in the variable pty_name. */
201
202 static int
203 allocate_pty (void)
204 {
205 #ifndef PTY_OPEN
206 struct stat stb;
207
208 /* Some systems name their pseudoterminals so that there are gaps in
209 the usual sequence - for example, on HP9000/S700 systems, there
210 are no pseudoterminals with names ending in 'f'. So we wait for
211 three failures in a row before deciding that we've reached the
212 end of the ptys. */
213 int failed_count = 0;
214 #endif
215 int fd;
216 #ifndef HAVE_GETPT
217 int i;
218 int c;
219 #endif
220
221 #ifdef PTY_ITERATION
222 PTY_ITERATION
223 #else
224 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
225 for (i = 0; i < 16; i++)
226 #endif
227 {
228 #ifdef PTY_NAME_SPRINTF
229 PTY_NAME_SPRINTF
230 #else
231 sprintf (pty_name, "/dev/pty%c%x", c, i);
232 #endif /* no PTY_NAME_SPRINTF */
233
234 #ifdef PTY_OPEN
235 PTY_OPEN;
236 #else /* no PTY_OPEN */
237 #ifdef IRIS
238 /* Unusual IRIS code */
239 *ptyv = open ("/dev/ptc", O_RDWR | O_NONBLOCK | OPEN_BINARY, 0);
240 if (fd < 0)
241 return -1;
242 if (fstat (fd, &stb) < 0)
243 return -1;
244 #else /* not IRIS */
245 if (stat (pty_name, &stb) < 0)
246 {
247 failed_count++;
248 if (failed_count >= 3)
249 return -1;
250 }
251 else
252 failed_count = 0;
253 fd = open (pty_name, O_RDWR | O_NONBLOCK | OPEN_BINARY, 0);
254 #endif /* not IRIS */
255 #endif /* no PTY_OPEN */
256
257 if (fd >= 0)
258 {
259 /* check to make certain that both sides are available
260 this avoids a nasty yet stupid bug in rlogins */
261 #ifdef PTY_TTY_NAME_SPRINTF
262 PTY_TTY_NAME_SPRINTF
263 #else
264 sprintf (pty_name, "/dev/tty%c%x", c, i);
265 #endif /* no PTY_TTY_NAME_SPRINTF */
266 #if !defined(UNIPLUS) && !defined(HAVE_GETPT)
267 if (access (pty_name, 6) != 0)
268 {
269 close (fd);
270 #if !defined(IRIS) && !defined(__sgi)
271 continue;
272 #else
273 return -1;
274 #endif /* IRIS */
275 }
276 #endif /* not UNIPLUS */
277 setup_pty (fd);
278 return fd;
279 }
280 }
281 return -1;
282 }
283 #endif /* HAVE_PTYS */
284
285 static int
286 create_bidirectional_pipe (int *inchannel, int *outchannel,
287 volatile int *forkin, volatile int *forkout)
288 {
289 int sv[2];
290
291 #ifdef SKTPAIR
292 if (socketpair (AF_UNIX, SOCK_STREAM, 0, sv) < 0)
293 return -1;
294 *outchannel = *inchannel = sv[0];
295 *forkout = *forkin = sv[1];
296 #else /* not SKTPAIR */
297 int temp;
298 temp = pipe (sv);
299 if (temp < 0) return -1;
300 *inchannel = sv[0];
301 *forkout = sv[1];
302 temp = pipe (sv);
303 if (temp < 0) return -1;
304 *outchannel = sv[1];
305 *forkin = sv[0];
306 #endif /* not SKTPAIR */
307 return 0;
308 }
309
310
311 #ifdef HAVE_SOCKETS
312
313 static int
314 get_internet_address (Lisp_Object host, struct sockaddr_in *address,
315 Error_behavior errb)
316 {
317 struct hostent *host_info_ptr = NULL;
318 #ifdef TRY_AGAIN
319 int count = 0;
320 #endif
321
322 xzero (*address);
323
324 while (1)
325 {
326 #ifdef TRY_AGAIN
327 if (count++ > 10) break;
328 #ifndef BROKEN_CYGWIN
329 h_errno = 0;
330 #endif
331 #endif
332 /* Some systems can't handle SIGIO/SIGALARM in gethostbyname. */
333 slow_down_interrupts ();
334 host_info_ptr = gethostbyname ((char *) XSTRING_DATA (host));
335 speed_up_interrupts ();
336 #ifdef TRY_AGAIN
337 if (! (host_info_ptr == 0 && h_errno == TRY_AGAIN))
338 #endif
339 break;
340 Fsleep_for (make_int (1));
341 }
342 if (host_info_ptr)
343 {
344 address->sin_family = host_info_ptr->h_addrtype;
345 memcpy (&address->sin_addr, host_info_ptr->h_addr, host_info_ptr->h_length);
346 }
347 else
348 {
349 IN_ADDR numeric_addr;
350 /* Attempt to interpret host as numeric inet address */
351 numeric_addr = inet_addr ((char *) XSTRING_DATA (host));
352 if (NUMERIC_ADDR_ERROR)
353 {
354 maybe_error (Qprocess, errb,
355 "Unknown host \"%s\"", XSTRING_DATA (host));
356 return 0;
357 }
358
359 /* There was some broken code here that called strlen() here
360 on (char *) &numeric_addr and even sometimes accessed
361 uninitialized data. */
362 address->sin_family = AF_INET;
363 * (IN_ADDR *) &address->sin_addr = numeric_addr;
364 }
365
366 return 1;
367 }
368
369 static void
370 set_socket_nonblocking_maybe (int fd, int port, CONST char* proto)
371 {
372 #ifdef PROCESS_IO_BLOCKING
373 Lisp_Object tail;
374
375 for (tail = network_stream_blocking_port_list; CONSP (tail); tail = XCDR (tail))
376 {
377 Lisp_Object tail_port = XCAR (tail);
378
379 if (STRINGP (tail_port))
380 {
381 struct servent *svc_info;
382 CHECK_STRING (tail_port);
383 svc_info = getservbyname ((char *) XSTRING_DATA (tail_port), proto);
384 if ((svc_info != 0) && (svc_info->s_port == port))
385 break;
386 else
387 continue;
388 }
389 else if (INTP (tail_port) && (htons ((unsigned short) XINT (tail_port)) == port))
390 break;
391 }
392
393 if (!CONSP (tail))
394 {
395 set_descriptor_non_blocking (fd);
396 }
397 #else
398 set_descriptor_non_blocking (fd);
399 #endif /* PROCESS_IO_BLOCKING */
400 }
401
402 #endif /* HAVE_SOCKETS */
403
404 /* Compute the Lisp form of the process status from
405 the numeric status that was returned by `wait'. */
406
407 static void
408 update_status_from_wait_code (struct Lisp_Process *p, int *w_fmh)
409 {
410 /* C compiler lossage when attempting to pass w directly */
411 int w = *w_fmh;
412
413 if (WIFSTOPPED (w))
414 {
415 p->status_symbol = Qstop;
416 p->exit_code = WSTOPSIG (w);
417 p->core_dumped = 0;
418 }
419 else if (WIFEXITED (w))
420 {
421 p->status_symbol = Qexit;
422 p->exit_code = WEXITSTATUS (w);
423 p->core_dumped = 0;
424 }
425 else if (WIFSIGNALED (w))
426 {
427 p->status_symbol = Qsignal;
428 p->exit_code = WTERMSIG (w);
429 p->core_dumped = WCOREDUMP (w);
430 }
431 else
432 {
433 p->status_symbol = Qrun;
434 p->exit_code = 0;
435 }
436 }
437
438 #ifdef SIGCHLD
439
440 #define MAX_EXITED_PROCESSES 1000
441 static volatile pid_t exited_processes[MAX_EXITED_PROCESSES];
442 static volatile int exited_processes_status[MAX_EXITED_PROCESSES];
443 static volatile int exited_processes_index;
444
445 static volatile int sigchld_happened;
446
447 /* On receipt of a signal that a child status has changed,
448 loop asking about children with changed statuses until
449 the system says there are no more. All we do is record
450 the processes and wait status.
451
452 This function could be called from within the SIGCHLD
453 handler, so it must be completely reentrant. When
454 not called from a SIGCHLD handler, BLOCK_SIGCHLD should
455 be non-zero so that SIGCHLD is blocked while this
456 function is running. (This is necessary so avoid
457 race conditions with the SIGCHLD_HAPPENED flag). */
458
459 static void
460 record_exited_processes (int block_sigchld)
461 {
462 if (!sigchld_happened)
463 {
464 return;
465 }
466
467 #ifdef EMACS_BLOCK_SIGNAL
468 if (block_sigchld)
469 EMACS_BLOCK_SIGNAL (SIGCHLD);
470 #endif
471
472 while (sigchld_happened)
473 {
474 int pid;
475 int w;
476
477 /* Keep trying to get a status until we get a definitive result. */
478 do
479 {
480 errno = 0;
481 #ifdef WNOHANG
482 # ifndef WUNTRACED
483 # define WUNTRACED 0
484 # endif /* not WUNTRACED */
485 # ifdef HAVE_WAITPID
486 pid = waitpid ((pid_t) -1, &w, WNOHANG | WUNTRACED);
487 # else
488 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
489 # endif
490 #else /* not WNOHANG */
491 pid = wait (&w);
492 #endif /* not WNOHANG */
493 }
494 while (pid <= 0 && errno == EINTR);
495
496 if (pid <= 0)
497 break;
498
499 if (exited_processes_index < MAX_EXITED_PROCESSES)
500 {
501 exited_processes[exited_processes_index] = pid;
502 exited_processes_status[exited_processes_index] = w;
503 exited_processes_index++;
504 }
505
506 /* On systems with WNOHANG, we just ignore the number
507 of times that SIGCHLD was signalled, and keep looping
508 until there are no more processes to wait on. If we
509 don't have WNOHANG, we have to rely on the count in
510 SIGCHLD_HAPPENED. */
511 #ifndef WNOHANG
512 sigchld_happened--;
513 #endif /* not WNOHANG */
514 }
515
516 sigchld_happened = 0;
517
518 if (block_sigchld)
519 EMACS_UNBLOCK_SIGNAL (SIGCHLD);
520 }
521
522 /* For any processes that have changed status and are recorded
523 and such, update the corresponding struct Lisp_Process.
524 We separate this from record_exited_processes() so that
525 we never have to call this function from within a signal
526 handler. We block SIGCHLD in case record_exited_processes()
527 is called from a signal handler. */
528
529 /** USG WARNING: Although it is not obvious from the documentation
530 in signal(2), on a USG system the SIGCLD handler MUST NOT call
531 signal() before executing at least one wait(), otherwise the handler
532 will be called again, resulting in an infinite loop. The relevant
533 portion of the documentation reads "SIGCLD signals will be queued
534 and the signal-catching function will be continually reentered until
535 the queue is empty". Invoking signal() causes the kernel to reexamine
536 the SIGCLD queue. Fred Fish, UniSoft Systems Inc.
537
538 (Note that now this only applies in SYS V Release 2 and before.
539 On SYS V Release 3, we use sigset() to set the signal handler for
540 the first time, and so we don't have to reestablish the signal handler
541 in the handler below. On SYS V Release 4, we don't get this weirdo
542 behavior when we use sigaction(), which we do use.) */
543
544 static SIGTYPE
545 sigchld_handler (int signo)
546 {
547 #ifdef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
548 int old_errno = errno;
549
550 sigchld_happened++;
551 record_exited_processes (0);
552 errno = old_errno;
553 #else
554 sigchld_happened++;
555 #endif
556 #ifdef HAVE_UNIXOID_EVENT_LOOP
557 signal_fake_event ();
558 #endif
559 /* WARNING - must come after wait3() for USG systems */
560 EMACS_REESTABLISH_SIGNAL (signo, sigchld_handler);
561 SIGRETURN;
562 }
563
564 #endif /* SIGCHLD */
565
566 #ifdef SIGNALS_VIA_CHARACTERS
567 /* Get signal character to send to process if SIGNALS_VIA_CHARACTERS */
568
569 static int
570 process_signal_char (int tty_fd, int signo)
571 {
572 /* If it's not a tty, pray that these default values work */
573 if (!isatty(tty_fd)) {
574 #define CNTL(ch) (037 & (ch))
575 switch (signo)
576 {
577 case SIGINT: return CNTL('C');
578 case SIGQUIT: return CNTL('\\');
579 #ifdef SIGTSTP
580 case SIGTSTP: return CNTL('Z');
581 #endif
582 }
583 }
584
585 #ifdef HAVE_TERMIOS
586 /* TERMIOS is the latest and bestest, and seems most likely to work.
587 If the system has it, use it. */
588 {
589 struct termios t;
590 tcgetattr (tty_fd, &t);
591 switch (signo)
592 {
593 case SIGINT: return t.c_cc[VINTR];
594 case SIGQUIT: return t.c_cc[VQUIT];
595 #if defined(SIGTSTP) && defined(VSUSP)
596 case SIGTSTP: return t.c_cc[VSUSP];
597 #endif
598 }
599 }
600
601 # elif defined (TIOCGLTC) && defined (TIOCGETC) /* not HAVE_TERMIOS */
602 {
603 /* On Berkeley descendants, the following IOCTL's retrieve the
604 current control characters. */
605 struct tchars c;
606 struct ltchars lc;
607 switch (signo)
608 {
609 case SIGINT: ioctl (tty_fd, TIOCGETC, &c); return c.t_intrc;
610 case SIGQUIT: ioctl (tty_fd, TIOCGETC, &c); return c.t_quitc;
611 # ifdef SIGTSTP
612 case SIGTSTP: ioctl (tty_fd, TIOCGLTC, &lc); return lc.t_suspc;
613 # endif /* SIGTSTP */
614 }
615 }
616
617 # elif defined (TCGETA) /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
618 {
619 /* On SYSV descendants, the TCGETA ioctl retrieves the current
620 control characters. */
621 struct termio t;
622 ioctl (tty_fd, TCGETA, &t);
623 switch (signo) {
624 case SIGINT: return t.c_cc[VINTR];
625 case SIGQUIT: return t.c_cc[VQUIT];
626 # ifdef SIGTSTP
627 case SIGTSTP: return t.c_cc[VSWTCH];
628 # endif /* SIGTSTP */
629 }
630 }
631 # else /* ! defined (TCGETA) */
632 #error ERROR! Using SIGNALS_VIA_CHARACTERS, but not HAVE_TERMIOS || (TIOCGLTC && TIOCGETC) || TCGETA
633 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
634 you'd better be using one of the alternatives above! */
635 # endif /* ! defined (TCGETA) */
636 return '\0';
637 }
638 #endif /* SIGNALS_VIA_CHARACTERS */
639
640
641
642
643 /**********************************************************************/
644 /* Process implementation methods */
645 /**********************************************************************/
646
647 /*
648 * Allocate and initialize Lisp_Process->process_data
649 */
650
651 static void
652 unix_alloc_process_data (struct Lisp_Process *p)
653 {
654 p->process_data = xnew (struct unix_process_data);
655
656 UNIX_DATA(p)->connected_via_filedesc_p = 0;
657 UNIX_DATA(p)->infd = -1;
658 UNIX_DATA(p)->subtty = -1;
659 UNIX_DATA(p)->tty_name = Qnil;
660 UNIX_DATA(p)->pty_flag = 0;
661 }
662
663 /*
664 * Mark any Lisp objects in Lisp_Process->process_data
665 */
666
667 static void
668 unix_mark_process_data (struct Lisp_Process *proc)
669 {
670 mark_object (UNIX_DATA(proc)->tty_name);
671 }
672
673 /*
674 * Initialize XEmacs process implementation once
675 */
676
677 #ifdef SIGCHLD
678 static void
679 unix_init_process (void)
680 {
681 #ifndef CANNOT_DUMP
682 if (! noninteractive || initialized)
683 #endif
684 signal (SIGCHLD, sigchld_handler);
685 }
686 #endif /* SIGCHLD */
687
688 /*
689 * Initialize any process local data. This is called when newly
690 * created process is connected to real OS file handles. The
691 * handles are generally represented by void* type, but are
692 * of type int (file descriptors) for UNIX
693 */
694
695 static void
696 unix_init_process_io_handles (struct Lisp_Process *p, void* in, void* out, int flags)
697 {
698 UNIX_DATA(p)->infd = (int)in;
699 }
700
701 /*
702 * Fork off a subprocess. P is a pointer to a newly created subprocess
703 * object. If this function signals, the caller is responsible for
704 * deleting (and finalizing) the process object.
705 *
706 * The method must return PID of the new process, a (positive??? ####) number
707 * which fits into Lisp_Int. No return value indicates an error, the method
708 * must signal an error instead.
709 */
710
711 static int
712 unix_create_process (struct Lisp_Process *p,
713 Lisp_Object *argv, int nargv,
714 Lisp_Object program, Lisp_Object cur_dir)
715 {
716 /* This function rewritten by ben@xemacs.org. */
717
718 int pid;
719 int inchannel = -1;
720 int outchannel = -1;
721 /* Use volatile to protect variables from being clobbered by longjmp. */
722 volatile int forkin = -1;
723 volatile int forkout = -1;
724 volatile int pty_flag = 0;
725
726 #ifdef HAVE_PTYS
727 if (!NILP (Vprocess_connection_type))
728 {
729 /* find a new pty, open the master side, return the opened
730 file handle, and store the name of the corresponding slave
731 side in global variable pty_name. */
732 outchannel = inchannel = allocate_pty ();
733 }
734
735 if (inchannel >= 0)
736 {
737 /* You're "supposed" to now open the slave in the child.
738 On some systems, we can open it here; this allows for
739 better error checking. */
740 #if !defined(USG)
741 /* On USG systems it does not work to open the pty's tty here
742 and then close and reopen it in the child. */
743 #ifdef O_NOCTTY
744 /* Don't let this terminal become our controlling terminal
745 (in case we don't have one). */
746 forkout = forkin = open (pty_name, O_RDWR | O_NOCTTY | OPEN_BINARY, 0);
747 #else
748 forkout = forkin = open (pty_name, O_RDWR | OPEN_BINARY, 0);
749 #endif
750 if (forkin < 0)
751 goto io_failure;
752 #endif /* not USG */
753 UNIX_DATA(p)->pty_flag = pty_flag = 1;
754 }
755 else
756 #endif /* HAVE_PTYS */
757 if (create_bidirectional_pipe (&inchannel, &outchannel,
758 &forkin, &forkout) < 0)
759 goto io_failure;
760
761 #if 0
762 /* Replaced by close_process_descs */
763 set_exclusive_use (inchannel);
764 set_exclusive_use (outchannel);
765 #endif
766
767 set_descriptor_non_blocking (inchannel);
768
769 /* Record this as an active process, with its channels.
770 As a result, child_setup will close Emacs's side of the pipes. */
771 init_process_io_handles (p, (void*)inchannel, (void*)outchannel,
772 pty_flag ? STREAM_PTY_FLUSHING : 0);
773 /* Record the tty descriptor used in the subprocess. */
774 UNIX_DATA(p)->subtty = forkin;
775
776 {
777 #if !defined(__CYGWIN32__)
778 /* child_setup must clobber environ on systems with true vfork.
779 Protect it from permanent change. */
780 char **save_environ = environ;
781 #endif
782
783 pid = fork ();
784 if (pid == 0)
785 {
786 /**** Now we're in the child process ****/
787 int xforkin = forkin;
788 int xforkout = forkout;
789
790 if (!pty_flag)
791 EMACS_SEPARATE_PROCESS_GROUP ();
792 #ifdef HAVE_PTYS
793 else
794 {
795 /* Disconnect the current controlling terminal, pursuant to
796 making the pty be the controlling terminal of the process.
797 Also put us in our own process group. */
798
799 disconnect_controlling_terminal ();
800
801 /* Open the pty connection and make the pty's terminal
802 our controlling terminal.
803
804 On systems with TIOCSCTTY, we just use it to set
805 the controlling terminal. On other systems, the
806 first TTY we open becomes the controlling terminal.
807 So, we end up with four possibilities:
808
809 (1) on USG and TIOCSCTTY systems, we open the pty
810 and use TIOCSCTTY.
811 (2) on other USG systems, we just open the pty.
812 (3) on non-USG systems with TIOCSCTTY, we
813 just use TIOCSCTTY. (On non-USG systems, we
814 already opened the pty in the parent process.)
815 (4) on non-USG systems without TIOCSCTTY, we
816 close the pty and reopen it.
817
818 This would be cleaner if we didn't open the pty
819 in the parent process, but doing it that way
820 makes it possible to trap error conditions.
821 It's harder to convey an error from the child
822 process, and I don't feel like messing with
823 this now. */
824
825 /* There was some weirdo, probably wrong,
826 conditionalization on RTU and UNIPLUS here.
827 I deleted it. So sue me. */
828
829 /* SunOS has TIOCSCTTY but the close/open method
830 also works. */
831
832 # if defined (USG) || !defined (TIOCSCTTY)
833 /* Now close the pty (if we had it open) and reopen it.
834 This makes the pty the controlling terminal of the
835 subprocess. */
836 /* I wonder if close (open (pty_name, ...)) would work? */
837 if (xforkin >= 0)
838 close (xforkin);
839 xforkout = xforkin = open (pty_name, O_RDWR | OPEN_BINARY, 0);
840 if (xforkin < 0)
841 {
842 write (1, "Couldn't open the pty terminal ", 31);
843 write (1, pty_name, strlen (pty_name));
844 write (1, "\n", 1);
845 _exit (1);
846 }
847 # endif /* USG or not TIOCSCTTY */
848
849 /* Miscellaneous setup required for some systems.
850 Must be done before using tc* functions on xforkin.
851 This guarantees that isatty(xforkin) is true. */
852
853 # ifdef SETUP_SLAVE_PTY
854 SETUP_SLAVE_PTY;
855 # endif /* SETUP_SLAVE_PTY */
856
857 # ifdef TIOCSCTTY
858 /* We ignore the return value
859 because faith@cs.unc.edu says that is necessary on Linux. */
860 assert (isatty (xforkin));
861 ioctl (xforkin, TIOCSCTTY, 0);
862 # endif /* TIOCSCTTY */
863
864 /* Change the line discipline. */
865
866 # if defined (HAVE_TERMIOS) && defined (LDISC1)
867 {
868 struct termios t;
869 assert (isatty (xforkin));
870 tcgetattr (xforkin, &t);
871 t.c_lflag = LDISC1;
872 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
873 perror ("create_process/tcsetattr LDISC1 failed\n");
874 }
875 # elif defined (NTTYDISC) && defined (TIOCSETD)
876 {
877 /* Use new line discipline. TIOCSETD is accepted and
878 ignored on Sys5.4 systems with ttcompat. */
879 int ldisc = NTTYDISC;
880 assert (isatty (xforkin));
881 ioctl (xforkin, TIOCSETD, &ldisc);
882 }
883 # endif /* TIOCSETD & NTTYDISC */
884
885 /* Make our process group be the foreground group
886 of our new controlling terminal. */
887
888 {
889 int piddly = EMACS_GET_PROCESS_GROUP ();
890 EMACS_SET_TTY_PROCESS_GROUP (xforkin, &piddly);
891 }
892
893 /* On AIX, we've disabled SIGHUP above once we start a
894 child on a pty. Now reenable it in the child, so it
895 will die when we want it to.
896 JV: This needs to be done ALWAYS as we might have inherited
897 a SIG_IGN handling from our parent (nohup) and we are in new
898 process group.
899 */
900 signal (SIGHUP, SIG_DFL);
901 }
902
903 if (pty_flag)
904 /* Set up the terminal characteristics of the pty. */
905 child_setup_tty (xforkout);
906
907 #endif /* HAVE_PTYS */
908
909 signal (SIGINT, SIG_DFL);
910 signal (SIGQUIT, SIG_DFL);
911
912 {
913 char *current_dir;
914 char **new_argv = alloca_array (char *, nargv + 2);
915 int i;
916
917 /* Nothing below here GCs so our string pointers shouldn't move. */
918 new_argv[0] = (char *) XSTRING_DATA (program);
919 for (i = 0; i < nargv; i++)
920 {
921 CHECK_STRING (argv[i]);
922 new_argv[i + 1] = (char *) XSTRING_DATA (argv[i]);
923 }
924 new_argv[i + 1] = 0;
925
926 GET_C_STRING_FILENAME_DATA_ALLOCA (cur_dir, current_dir);
927
928 child_setup (xforkin, xforkout, xforkout, new_argv, current_dir);
929 }
930
931 } /**** End of child code ****/
932
933 /**** Back in parent process ****/
934 #if !defined(__CYGWIN32__)
935 environ = save_environ;
936 #endif
937 }
938
939 if (pid < 0)
940 {
941 close_descriptor_pair (forkin, forkout);
942 report_file_error ("Doing fork", Qnil);
943 }
944
945 /* #### dmoore - why is this commented out, otherwise we leave
946 subtty = forkin, but then we close forkin just below. */
947 /* UNIX_DATA(p)->subtty = -1; */
948
949 /* If the subfork execv fails, and it exits,
950 this close hangs. I don't know why.
951 So have an interrupt jar it loose. */
952 if (forkin >= 0)
953 close_safely (forkin);
954 if (forkin != forkout && forkout >= 0)
955 close (forkout);
956
957 #ifdef HAVE_PTYS
958 if (pty_flag)
959 UNIX_DATA (p)->tty_name = build_string (pty_name);
960 else
961 #endif
962 UNIX_DATA (p)->tty_name = Qnil;
963
964 /* Notice that SIGCHLD was not blocked. (This is not possible on
965 some systems.) No biggie if SIGCHLD occurs right around the
966 time that this call happens, because SIGCHLD() does not actually
967 deselect the process (that doesn't occur until the next time
968 we're waiting for an event, when status_notify() is called). */
969 return pid;
970
971 io_failure:
972 {
973 int save_errno = errno;
974 close_descriptor_pair (forkin, forkout);
975 close_descriptor_pair (inchannel, outchannel);
976 errno = save_errno;
977 report_file_error ("Opening pty or pipe", Qnil);
978 return 0; /* not reached */
979 }
980 }
981
982 /* Return nonzero if this process is a ToolTalk connection. */
983
984 static int
985 unix_tooltalk_connection_p (struct Lisp_Process *p)
986 {
987 return UNIX_DATA(p)->connected_via_filedesc_p;
988 }
989
990 /* This is called to set process' virtual terminal size */
991
992 static int
993 unix_set_window_size (struct Lisp_Process* p, int cols, int rows)
994 {
995 return set_window_size (UNIX_DATA(p)->infd, cols, rows);
996 }
997
998 /*
999 * This method is called to update status fields of the process
1000 * structure. If the process has not existed, this method is
1001 * expected to do nothing.
1002 *
1003 * The method is called only for real child processes.
1004 */
1005
1006 #ifdef HAVE_WAITPID
1007 static void
1008 unix_update_status_if_terminated (struct Lisp_Process* p)
1009 {
1010 int w;
1011 #ifdef SIGCHLD
1012 EMACS_BLOCK_SIGNAL (SIGCHLD);
1013 #endif
1014 if (waitpid (XINT (p->pid), &w, WNOHANG) == XINT (p->pid))
1015 {
1016 p->tick++;
1017 update_status_from_wait_code (p, &w);
1018 }
1019 #ifdef SIGCHLD
1020 EMACS_UNBLOCK_SIGNAL (SIGCHLD);
1021 #endif
1022 }
1023 #endif
1024
1025 /*
1026 * Update status of all exited processes. Called when SIGCLD has signaled.
1027 */
1028
1029 #ifdef SIGCHLD
1030 static void
1031 unix_reap_exited_processes (void)
1032 {
1033 int i;
1034 struct Lisp_Process *p;
1035
1036 #ifndef OBNOXIOUS_SYSV_SIGCLD_BEHAVIOR
1037 record_exited_processes (1);
1038 #endif
1039
1040 if (exited_processes_index <= 0)
1041 {
1042 return;
1043 }
1044
1045 #ifdef EMACS_BLOCK_SIGNAL
1046 EMACS_BLOCK_SIGNAL (SIGCHLD);
1047 #endif
1048 for (i = 0; i < exited_processes_index; i++)
1049 {
1050 int pid = exited_processes[i];
1051 int w = exited_processes_status[i];
1052
1053 /* Find the process that signaled us, and record its status. */
1054
1055 p = 0;
1056 {
1057 Lisp_Object tail;
1058 LIST_LOOP (tail, Vprocess_list)
1059 {
1060 Lisp_Object proc = XCAR (tail);
1061 p = XPROCESS (proc);
1062 if (INTP (p->pid) && XINT (p->pid) == pid)
1063 break;
1064 p = 0;
1065 }
1066 }
1067
1068 if (p)
1069 {
1070 /* Change the status of the process that was found. */
1071 p->tick++;
1072 process_tick++;
1073 update_status_from_wait_code (p, &w);
1074
1075 /* If process has terminated, stop waiting for its output. */
1076 if (WIFSIGNALED (w) || WIFEXITED (w))
1077 {
1078 if (!NILP(p->pipe_instream))
1079 {
1080 /* We can't just call event_stream->unselect_process_cb (p)
1081 here, because that calls XtRemoveInput, which is not
1082 necessarily reentrant, so we can't call this at interrupt
1083 level.
1084 */
1085 }
1086 }
1087 }
1088 else
1089 {
1090 /* There was no asynchronous process found for that id. Check
1091 if we have a synchronous process. Only set sync process status
1092 if there is one, so we work OK with the waitpid() call in
1093 wait_for_termination(). */
1094 if (synch_process_alive != 0)
1095 { /* Set the global sync process status variables. */
1096 synch_process_alive = 0;
1097
1098 /* Report the status of the synchronous process. */
1099 if (WIFEXITED (w))
1100 synch_process_retcode = WEXITSTATUS (w);
1101 else if (WIFSIGNALED (w))
1102 synch_process_death = signal_name (WTERMSIG (w));
1103 }
1104 }
1105 }
1106
1107 exited_processes_index = 0;
1108
1109 EMACS_UNBLOCK_SIGNAL (SIGCHLD);
1110 }
1111 #endif /* SIGCHLD */
1112
1113 /*
1114 * Stuff the entire contents of LSTREAM to the process output pipe
1115 */
1116
1117 static JMP_BUF send_process_frame;
1118
1119 static SIGTYPE
1120 send_process_trap (int signum)
1121 {
1122 EMACS_REESTABLISH_SIGNAL (signum, send_process_trap);
1123 EMACS_UNBLOCK_SIGNAL (signum);
1124 LONGJMP (send_process_frame, 1);
1125 }
1126
1127 static void
1128 unix_send_process (Lisp_Object proc, struct lstream* lstream)
1129 {
1130 /* Use volatile to protect variables from being clobbered by longjmp. */
1131 SIGTYPE (*volatile old_sigpipe) (int) = 0;
1132 volatile Lisp_Object vol_proc = proc;
1133 struct Lisp_Process *volatile p = XPROCESS (proc);
1134
1135 if (!SETJMP (send_process_frame))
1136 {
1137 /* use a reasonable-sized buffer (somewhere around the size of the
1138 stream buffer) so as to avoid inundating the stream with blocked
1139 data. */
1140 Bufbyte chunkbuf[512];
1141 Bytecount chunklen;
1142
1143 while (1)
1144 {
1145 ssize_t writeret;
1146
1147 chunklen = Lstream_read (lstream, chunkbuf, 512);
1148 if (chunklen <= 0)
1149 break; /* perhaps should abort() if < 0?
1150 This should never happen. */
1151 old_sigpipe =
1152 (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
1153 /* Lstream_write() will never successfully write less than
1154 the amount sent in. In the worst case, it just buffers
1155 the unwritten data. */
1156 writeret = Lstream_write (XLSTREAM (DATA_OUTSTREAM(p)), chunkbuf,
1157 chunklen);
1158 signal (SIGPIPE, old_sigpipe);
1159 if (writeret < 0)
1160 /* This is a real error. Blocking errors are handled
1161 specially inside of the filedesc stream. */
1162 report_file_error ("writing to process", list1 (proc));
1163 while (Lstream_was_blocked_p (XLSTREAM (p->pipe_outstream)))
1164 {
1165 /* Buffer is full. Wait, accepting input;
1166 that may allow the program
1167 to finish doing output and read more. */
1168 Faccept_process_output (Qnil, make_int (1), Qnil);
1169 old_sigpipe =
1170 (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
1171 Lstream_flush (XLSTREAM (p->pipe_outstream));
1172 signal (SIGPIPE, old_sigpipe);
1173 }
1174 }
1175 }
1176 else
1177 { /* We got here from a longjmp() from the SIGPIPE handler */
1178 signal (SIGPIPE, old_sigpipe);
1179 /* Close the file lstream so we don't attempt to write to it further */
1180 /* #### There is controversy over whether this might cause fd leakage */
1181 /* my tests say no. -slb */
1182 XLSTREAM (p->pipe_outstream)->flags &= ~LSTREAM_FL_IS_OPEN;
1183 p->status_symbol = Qexit;
1184 p->exit_code = 256; /* #### SIGPIPE ??? */
1185 p->core_dumped = 0;
1186 p->tick++;
1187 process_tick++;
1188 deactivate_process (*((Lisp_Object *) (&vol_proc)));
1189 error ("SIGPIPE raised on process %s; closed it",
1190 XSTRING_DATA (p->name));
1191 }
1192
1193 old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
1194 Lstream_flush (XLSTREAM (DATA_OUTSTREAM(p)));
1195 signal (SIGPIPE, old_sigpipe);
1196 }
1197
1198 /*
1199 * Send EOF to the process. The default implementation simply
1200 * closes the output stream. The method must return 0 to call
1201 * the default implementation, or 1 if it has taken all care about
1202 * sending EOF to the process.
1203 */
1204
1205 static int
1206 unix_process_send_eof (Lisp_Object proc)
1207 {
1208 if (!UNIX_DATA (XPROCESS (proc))->pty_flag)
1209 return 0;
1210
1211 /* #### get_eof_char simply doesn't return the correct character
1212 here. Maybe it is needed to determine the right eof
1213 character in init_process_io_handles but here it simply screws
1214 things up. */
1215 #if 0
1216 Bufbyte eof_char = get_eof_char (XPROCESS (proc));
1217 send_process (proc, Qnil, &eof_char, 0, 1);
1218 #else
1219 send_process (proc, Qnil, (CONST Bufbyte *) "\004", 0, 1);
1220 #endif
1221 return 1;
1222 }
1223
1224 /*
1225 * Called before the process is deactivated. The process object
1226 * is not immediately finalized, just undergoes a transition to
1227 * inactive state.
1228 *
1229 * The return value is a unique stream ID, as returned by
1230 * event_stream_delete_stream_pair
1231 *
1232 * In the lack of this method, only event_stream_delete_stream_pair
1233 * is called on both I/O streams of the process.
1234 *
1235 * The UNIX version guards this by ignoring possible SIGPIPE.
1236 */
1237
1238 static USID
1239 unix_deactivate_process (struct Lisp_Process *p)
1240 {
1241 SIGTYPE (*old_sigpipe) (int) = 0;
1242 USID usid;
1243
1244 if (UNIX_DATA(p)->infd >= 0)
1245 flush_pending_output (UNIX_DATA(p)->infd);
1246
1247 /* closing the outstream could result in SIGPIPE, so ignore it. */
1248 old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, SIG_IGN);
1249 usid = event_stream_delete_stream_pair (p->pipe_instream, p->pipe_outstream);
1250 signal (SIGPIPE, old_sigpipe);
1251
1252 UNIX_DATA(p)->infd = -1;
1253
1254 return usid;
1255 }
1256
1257 /* send a signal number SIGNO to PROCESS.
1258 CURRENT_GROUP means send to the process group that currently owns
1259 the terminal being used to communicate with PROCESS.
1260 This is used for various commands in shell mode.
1261 If NOMSG is zero, insert signal-announcements into process's buffers
1262 right away.
1263
1264 If we can, we try to signal PROCESS by sending control characters
1265 down the pty. This allows us to signal inferiors who have changed
1266 their uid, for which killpg would return an EPERM error.
1267
1268 The method signals an error if the given SIGNO is not valid
1269 */
1270
1271 static void
1272 unix_kill_child_process (Lisp_Object proc, int signo,
1273 int current_group, int nomsg)
1274 {
1275 int gid;
1276 int no_pgrp = 0;
1277 int kill_retval;
1278 struct Lisp_Process *p = XPROCESS (proc);
1279
1280 if (!UNIX_DATA(p)->pty_flag)
1281 current_group = 0;
1282
1283 /* If we are using pgrps, get a pgrp number and make it negative. */
1284 if (current_group)
1285 {
1286 #ifdef SIGNALS_VIA_CHARACTERS
1287 /* If possible, send signals to the entire pgrp
1288 by sending an input character to it. */
1289 {
1290 char sigchar = process_signal_char(UNIX_DATA(p)->subtty, signo);
1291 if (sigchar) {
1292 send_process (proc, Qnil, (Bufbyte *) &sigchar, 0, 1);
1293 return;
1294 }
1295 }
1296 #endif /* ! defined (SIGNALS_VIA_CHARACTERS) */
1297
1298 #ifdef TIOCGPGRP
1299 /* Get the pgrp using the tty itself, if we have that.
1300 Otherwise, use the pty to get the pgrp.
1301 On pfa systems, saka@pfu.fujitsu.co.JP writes:
1302 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
1303 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
1304 His patch indicates that if TIOCGPGRP returns an error, then
1305 we should just assume that p->pid is also the process group id. */
1306 {
1307 int err;
1308
1309 err = ioctl ( (UNIX_DATA(p)->subtty != -1
1310 ? UNIX_DATA(p)->subtty
1311 : UNIX_DATA(p)->infd), TIOCGPGRP, &gid);
1312
1313 #ifdef pfa
1314 if (err == -1)
1315 gid = - XINT (p->pid);
1316 #endif /* ! defined (pfa) */
1317 }
1318 if (gid == -1)
1319 no_pgrp = 1;
1320 else
1321 gid = - gid;
1322 #else /* ! defined (TIOCGPGRP ) */
1323 /* Can't select pgrps on this system, so we know that
1324 the child itself heads the pgrp. */
1325 gid = - XINT (p->pid);
1326 #endif /* ! defined (TIOCGPGRP ) */
1327 }
1328 else
1329 gid = - XINT (p->pid);
1330
1331 switch (signo)
1332 {
1333 #ifdef SIGCONT
1334 case SIGCONT:
1335 p->status_symbol = Qrun;
1336 p->exit_code = 0;
1337 p->tick++;
1338 process_tick++;
1339 if (!nomsg)
1340 status_notify ();
1341 break;
1342 #endif /* ! defined (SIGCONT) */
1343 case SIGINT:
1344 case SIGQUIT:
1345 case SIGKILL:
1346 flush_pending_output (UNIX_DATA(p)->infd);
1347 break;
1348 }
1349
1350 /* If we don't have process groups, send the signal to the immediate
1351 subprocess. That isn't really right, but it's better than any
1352 obvious alternative. */
1353 if (no_pgrp)
1354 {
1355 kill_retval = kill (XINT (p->pid), signo) ? errno : 0;
1356 }
1357 else
1358 {
1359 /* gid may be a pid, or minus a pgrp's number */
1360 #if defined (TIOCSIGNAL) || defined (TIOCSIGSEND)
1361 if (current_group)
1362 {
1363 #ifdef TIOCSIGNAL
1364 kill_retval = ioctl (UNIX_DATA(p)->infd, TIOCSIGNAL, signo);
1365 #else /* ! defined (TIOCSIGNAL) */
1366 kill_retval = ioctl (UNIX_DATA(p)->infd, TIOCSIGSEND, signo);
1367 #endif /* ! defined (TIOCSIGNAL) */
1368 }
1369 else
1370 kill_retval = kill (- XINT (p->pid), signo) ? errno : 0;
1371 #else /* ! (defined (TIOCSIGNAL) || defined (TIOCSIGSEND)) */
1372 kill_retval = EMACS_KILLPG (-gid, signo) ? errno : 0;
1373 #endif /* ! (defined (TIOCSIGNAL) || defined (TIOCSIGSEND)) */
1374 }
1375
1376 if (kill_retval < 0 && errno == EINVAL)
1377 error ("Signal number %d is invalid for this system", signo);
1378 }
1379
1380 /*
1381 * Kill any process in the system given its PID.
1382 *
1383 * Returns zero if a signal successfully sent, or
1384 * negative number upon failure
1385 */
1386
1387 static int
1388 unix_kill_process_by_pid (int pid, int sigcode)
1389 {
1390 return kill (pid, sigcode);
1391 }
1392
1393 /*
1394 * Return TTY name used to communicate with subprocess
1395 */
1396
1397 static Lisp_Object
1398 unix_get_tty_name (struct Lisp_Process *p)
1399 {
1400 return UNIX_DATA (p)->tty_name;
1401 }
1402
1403 /*
1404 * Canonicalize host name HOST, and return its canonical form
1405 *
1406 * The default implementation just takes HOST for a canonical name.
1407 */
1408
1409 #ifdef HAVE_SOCKETS
1410 static Lisp_Object
1411 unix_canonicalize_host_name (Lisp_Object host)
1412 {
1413 struct sockaddr_in address;
1414
1415 if (!get_internet_address (host, &address, ERROR_ME_NOT))
1416 return host;
1417
1418 if (address.sin_family == AF_INET)
1419 return build_string (inet_ntoa (address.sin_addr));
1420 else
1421 /* #### any clue what to do here? */
1422 return host;
1423 }
1424
1425 /* open a TCP network connection to a given HOST/SERVICE. Treated
1426 exactly like a normal process when reading and writing. Only
1427 differences are in status display and process deletion. A network
1428 connection has no PID; you cannot signal it. All you can do is
1429 deactivate and close it via delete-process */
1430
1431 static void
1432 unix_open_network_stream (Lisp_Object name, Lisp_Object host, Lisp_Object service,
1433 Lisp_Object protocol, void** vinfd, void** voutfd)
1434 {
1435 struct sockaddr_in address;
1436 int inch;
1437 int outch;
1438 volatile int s;
1439 volatile int port;
1440 volatile int retry = 0;
1441 int retval;
1442
1443 CHECK_STRING (host);
1444
1445 if (!EQ (protocol, Qtcp) && !EQ (protocol, Qudp))
1446 error ("Unsupported protocol \"%s\"",
1447 string_data (symbol_name (XSYMBOL (protocol))));
1448
1449 if (INTP (service))
1450 port = htons ((unsigned short) XINT (service));
1451 else
1452 {
1453 struct servent *svc_info;
1454 CHECK_STRING (service);
1455
1456 if (EQ (protocol, Qtcp))
1457 svc_info = getservbyname ((char *) XSTRING_DATA (service), "tcp");
1458 else /* EQ (protocol, Qudp) */
1459 svc_info = getservbyname ((char *) XSTRING_DATA (service), "udp");
1460
1461 if (svc_info == 0)
1462 error ("Unknown service \"%s\"", XSTRING_DATA (service));
1463 port = svc_info->s_port;
1464 }
1465
1466 get_internet_address (host, &address, ERROR_ME);
1467 address.sin_port = port;
1468
1469 if (EQ (protocol, Qtcp))
1470 s = socket (address.sin_family, SOCK_STREAM, 0);
1471 else /* EQ (protocol, Qudp) */
1472 s = socket (address.sin_family, SOCK_DGRAM, 0);
1473
1474 if (s < 0)
1475 report_file_error ("error creating socket", list1 (name));
1476
1477 /* Turn off interrupts here -- see comments below. There used to
1478 be code which called bind_polling_period() to slow the polling
1479 period down rather than turn it off, but that seems rather
1480 bogus to me. Best thing here is to use a non-blocking connect
1481 or something, to check for QUIT. */
1482
1483 /* Comments that are not quite valid: */
1484
1485 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
1486 when connect is interrupted. So let's not let it get interrupted.
1487 Note we do not turn off polling, because polling is only used
1488 when not interrupt_input, and thus not normally used on the systems
1489 which have this bug. On systems which use polling, there's no way
1490 to quit if polling is turned off. */
1491
1492 /* Slow down polling. Some kernels have a bug which causes retrying
1493 connect to fail after a connect. */
1494
1495 slow_down_interrupts ();
1496
1497 loop:
1498
1499 /* A system call interrupted with a SIGALRM or SIGIO comes back
1500 here, with can_break_system_calls reset to 0. */
1501 SETJMP (break_system_call_jump);
1502 if (QUITP)
1503 {
1504 speed_up_interrupts ();
1505 REALLY_QUIT;
1506 /* In case something really weird happens ... */
1507 slow_down_interrupts ();
1508 }
1509
1510 /* Break out of connect with a signal (it isn't otherwise possible).
1511 Thus you don't get screwed with a hung network. */
1512 can_break_system_calls = 1;
1513 retval = connect (s, (struct sockaddr *) &address, sizeof (address));
1514 can_break_system_calls = 0;
1515 if (retval == -1 && errno != EISCONN)
1516 {
1517 int xerrno = errno;
1518 if (errno == EINTR)
1519 goto loop;
1520 if (errno == EADDRINUSE && retry < 20)
1521 {
1522 /* A delay here is needed on some FreeBSD systems,
1523 and it is harmless, since this retrying takes time anyway
1524 and should be infrequent.
1525 `sleep-for' allowed for quitting this loop with interrupts
1526 slowed down so it can't be used here. Async timers should
1527 already be disabled at this point so we can use `sleep'. */
1528 sleep (1);
1529 retry++;
1530 goto loop;
1531 }
1532
1533 close (s);
1534
1535 speed_up_interrupts ();
1536
1537 errno = xerrno;
1538 report_file_error ("connection failed", list2 (host, name));
1539 }
1540
1541 speed_up_interrupts ();
1542
1543 inch = s;
1544 outch = dup (s);
1545 if (outch < 0)
1546 {
1547 close (s); /* this used to be leaked; from Kyle Jones */
1548 report_file_error ("error duplicating socket", list1 (name));
1549 }
1550
1551 set_socket_nonblocking_maybe (inch, port, "tcp");
1552
1553 *vinfd = (void*)inch;
1554 *voutfd = (void*)outch;
1555 }
1556
1557
1558 #ifdef HAVE_MULTICAST
1559
1560 /* Didier Verna <verna@inf.enst.fr> Nov. 28 1997.
1561
1562 This function is similar to open-network-stream-internal, but provides a
1563 mean to open an UDP multicast connection instead of a TCP one. Like in the
1564 TCP case, the multicast connection will be seen as a sub-process,
1565
1566 Some notes:
1567 - Normally, we should use sendto and recvfrom with non connected
1568 sockets. The current code doesn't allow us to do this. In the future, it
1569 would be a good idea to extend the process data structure in order to deal
1570 properly with the different types network connections.
1571 - For the same reason, when leaving a multicast group, it is better to make
1572 a setsockopt - IP_DROP_MEMBERSHIP before closing the descriptors.
1573 Unfortunately, this can't be done here because delete_process doesn't know
1574 about the kind of connection we have. However, this is not such an
1575 important issue.
1576 */
1577
1578 static void
1579 unix_open_multicast_group (Lisp_Object name, Lisp_Object dest, Lisp_Object port,
1580 Lisp_Object ttl, void** vinfd, void** voutfd)
1581 {
1582 struct ip_mreq imr;
1583 struct sockaddr_in sa;
1584 struct protoent *udp;
1585 int ws, rs;
1586 int theport;
1587 unsigned char thettl;
1588 int one = 1; /* For REUSEADDR */
1589 int ret;
1590 volatile int retry = 0;
1591
1592 CHECK_STRING (dest);
1593
1594 CHECK_NATNUM (port);
1595 theport = htons ((unsigned short) XINT (port));
1596
1597 CHECK_NATNUM (ttl);
1598 thettl = (unsigned char) XINT (ttl);
1599
1600 if ((udp = getprotobyname ("udp")) == NULL)
1601 error ("No info available for UDP protocol");
1602
1603 /* Init the sockets. Yes, I need 2 sockets. I couldn't duplicate one. */
1604 if ((rs = socket (PF_INET, SOCK_DGRAM, udp->p_proto)) < 0)
1605 report_file_error ("error creating socket", list1(name));
1606 if ((ws = socket (PF_INET, SOCK_DGRAM, udp->p_proto)) < 0)
1607 {
1608 close (rs);
1609 report_file_error ("error creating socket", list1(name));
1610 }
1611
1612 /* This will be used for both sockets */
1613 memset (&sa, 0, sizeof(sa));
1614 sa.sin_family = AF_INET;
1615 sa.sin_port = theport;
1616 sa.sin_addr.s_addr = htonl (inet_addr ((char *) XSTRING_DATA (dest)));
1617
1618 /* Socket configuration for reading ------------------------ */
1619
1620 /* Multiple connections from the same machine. This must be done before
1621 bind. If it fails, it shouldn't be fatal. The only consequence is that
1622 people won't be able to connect twice from the same machine. */
1623 if (setsockopt (rs, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof (one))
1624 < 0)
1625 warn_when_safe (Qmulticast, Qwarning, "Cannot reuse socket address");
1626
1627 /* bind socket name */
1628 if (bind (rs, (struct sockaddr *)&sa, sizeof(sa)))
1629 {
1630 close (rs);
1631 close (ws);
1632 report_file_error ("error binding socket", list2(name, port));
1633 }
1634
1635 /* join multicast group */
1636 imr.imr_multiaddr.s_addr = htonl (inet_addr ((char *) XSTRING_DATA (dest)));
1637 imr.imr_interface.s_addr = htonl (INADDR_ANY);
1638 if (setsockopt (rs, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1639 (char *) &imr, sizeof (struct ip_mreq)) < 0)
1640 {
1641 close (ws);
1642 close (rs);
1643 report_file_error ("error adding membership", list2(name, dest));
1644 }
1645
1646 /* Socket configuration for writing ----------------------- */
1647
1648 /* Normally, there's no 'connect' in multicast, since we prefer to use
1649 'sendto' and 'recvfrom'. However, in order to handle this connection in
1650 the process-like way it is done for TCP, we must be able to use 'write'
1651 instead of 'sendto'. Consequently, we 'connect' this socket. */
1652
1653 /* See open-network-stream-internal for comments on this part of the code */
1654 slow_down_interrupts ();
1655
1656 loop:
1657
1658 /* A system call interrupted with a SIGALRM or SIGIO comes back
1659 here, with can_break_system_calls reset to 0. */
1660 SETJMP (break_system_call_jump);
1661 if (QUITP)
1662 {
1663 speed_up_interrupts ();
1664 REALLY_QUIT;
1665 /* In case something really weird happens ... */
1666 slow_down_interrupts ();
1667 }
1668
1669 /* Break out of connect with a signal (it isn't otherwise possible).
1670 Thus you don't get screwed with a hung network. */
1671 can_break_system_calls = 1;
1672 ret = connect (ws, (struct sockaddr *) &sa, sizeof (sa));
1673 can_break_system_calls = 0;
1674 if (ret == -1 && errno != EISCONN)
1675 {
1676 int xerrno = errno;
1677
1678 if (errno == EINTR)
1679 goto loop;
1680 if (errno == EADDRINUSE && retry < 20)
1681 {
1682 /* A delay here is needed on some FreeBSD systems,
1683 and it is harmless, since this retrying takes time anyway
1684 and should be infrequent.
1685 `sleep-for' allowed for quitting this loop with interrupts
1686 slowed down so it can't be used here. Async timers should
1687 already be disabled at this point so we can use `sleep'. */
1688 sleep (1);
1689 retry++;
1690 goto loop;
1691 }
1692
1693 close (rs);
1694 close (ws);
1695 speed_up_interrupts ();
1696
1697 errno = xerrno;
1698 report_file_error ("error connecting socket", list2(name, port));
1699 }
1700
1701 speed_up_interrupts ();
1702
1703 /* scope */
1704 if (setsockopt (ws, IPPROTO_IP, IP_MULTICAST_TTL,
1705 (char *) &thettl, sizeof (thettl)) < 0)
1706 {
1707 close (rs);
1708 close (ws);
1709 report_file_error ("error setting ttl", list2(name, ttl));
1710 }
1711
1712 set_socket_nonblocking_maybe (rs, theport, "udp");
1713
1714 *vinfd = (void*)rs;
1715 *voutfd = (void*)ws;
1716 }
1717
1718 #endif /* HAVE_MULTICAST */
1719
1720 #endif /* HAVE_SOCKETS */
1721
1722
1723 /**********************************************************************/
1724 /* Initialization */
1725 /**********************************************************************/
1726
1727 void
1728 process_type_create_unix (void)
1729 {
1730 PROCESS_HAS_METHOD (unix, alloc_process_data);
1731 PROCESS_HAS_METHOD (unix, mark_process_data);
1732 #ifdef SIGCHLD
1733 PROCESS_HAS_METHOD (unix, init_process);
1734 PROCESS_HAS_METHOD (unix, reap_exited_processes);
1735 #endif
1736 PROCESS_HAS_METHOD (unix, init_process_io_handles);
1737 PROCESS_HAS_METHOD (unix, create_process);
1738 PROCESS_HAS_METHOD (unix, tooltalk_connection_p);
1739 PROCESS_HAS_METHOD (unix, set_window_size);
1740 #ifdef HAVE_WAITPID
1741 PROCESS_HAS_METHOD (unix, update_status_if_terminated);
1742 #endif
1743 PROCESS_HAS_METHOD (unix, send_process);
1744 PROCESS_HAS_METHOD (unix, process_send_eof);
1745 PROCESS_HAS_METHOD (unix, deactivate_process);
1746 PROCESS_HAS_METHOD (unix, kill_child_process);
1747 PROCESS_HAS_METHOD (unix, kill_process_by_pid);
1748 PROCESS_HAS_METHOD (unix, get_tty_name);
1749 #ifdef HAVE_SOCKETS
1750 PROCESS_HAS_METHOD (unix, canonicalize_host_name);
1751 PROCESS_HAS_METHOD (unix, open_network_stream);
1752 #ifdef HAVE_MULTICAST
1753 PROCESS_HAS_METHOD (unix, open_multicast_group);
1754 #endif
1755 #endif
1756 }
1757
1758 void
1759 vars_of_process_unix (void)
1760 {
1761 Fprovide (intern ("unix-processes"));
1762 }
1763
1764 #endif /* !defined (NO_SUBPROCESSES) */