Generalize run-time debugging checks.
[bpt/emacs.git] / src / process.c
1 /* Asynchronous subprocess control for GNU Emacs.
2
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2012
4 Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21
22 #include <config.h>
23 #include <signal.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <setjmp.h>
27 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
28 #include <sys/file.h>
29 #include <sys/stat.h>
30 #include <setjmp.h>
31
32 #include <unistd.h>
33 #include <fcntl.h>
34
35 #include "lisp.h"
36
37 /* Only MS-DOS does not define `subprocesses'. */
38 #ifdef subprocesses
39
40 #include <sys/socket.h>
41 #include <netdb.h>
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
44
45 /* Are local (unix) sockets supported? */
46 #if defined (HAVE_SYS_UN_H)
47 #if !defined (AF_LOCAL) && defined (AF_UNIX)
48 #define AF_LOCAL AF_UNIX
49 #endif
50 #ifdef AF_LOCAL
51 #define HAVE_LOCAL_SOCKETS
52 #include <sys/un.h>
53 #endif
54 #endif
55
56 #include <sys/ioctl.h>
57 #if defined (HAVE_NET_IF_H)
58 #include <net/if.h>
59 #endif /* HAVE_NET_IF_H */
60
61 #if defined (HAVE_IFADDRS_H)
62 /* Must be after net/if.h */
63 #include <ifaddrs.h>
64
65 /* We only use structs from this header when we use getifaddrs. */
66 #if defined (HAVE_NET_IF_DL_H)
67 #include <net/if_dl.h>
68 #endif
69
70 #endif
71
72 #ifdef NEED_BSDTTY
73 #include <bsdtty.h>
74 #endif
75
76 #ifdef HAVE_RES_INIT
77 #include <netinet/in.h>
78 #include <arpa/nameser.h>
79 #include <resolv.h>
80 #endif
81
82 #ifdef HAVE_UTIL_H
83 #include <util.h>
84 #endif
85
86 #ifdef HAVE_PTY_H
87 #include <pty.h>
88 #endif
89
90 #endif /* subprocesses */
91
92 #include "systime.h"
93 #include "systty.h"
94
95 #include "window.h"
96 #include "character.h"
97 #include "buffer.h"
98 #include "coding.h"
99 #include "process.h"
100 #include "frame.h"
101 #include "termhooks.h"
102 #include "termopts.h"
103 #include "commands.h"
104 #include "keyboard.h"
105 #include "blockinput.h"
106 #include "dispextern.h"
107 #include "composite.h"
108 #include "atimer.h"
109 #include "sysselect.h"
110 #include "syssignal.h"
111 #include "syswait.h"
112 #ifdef HAVE_GNUTLS
113 #include "gnutls.h"
114 #endif
115
116 #if defined (USE_GTK) || defined (HAVE_GCONF) || defined (HAVE_GSETTINGS)
117 #include "xgselect.h"
118 #endif
119 #ifdef HAVE_NS
120 #include "nsterm.h"
121 #endif
122
123 /* Work around GCC 4.7.0 bug with strict overflow checking; see
124 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
125 These lines can be removed once the GCC bug is fixed. */
126 #if (__GNUC__ == 4 && 3 <= __GNUC_MINOR__) || 4 < __GNUC__
127 # pragma GCC diagnostic ignored "-Wstrict-overflow"
128 #endif
129
130 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
131 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
132 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
133 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
134 Lisp_Object QCname, QCtype;
135 \f
136 /* Non-zero if keyboard input is on hold, zero otherwise. */
137
138 static int kbd_is_on_hold;
139
140 /* Nonzero means don't run process sentinels. This is used
141 when exiting. */
142 int inhibit_sentinels;
143
144 #ifdef subprocesses
145
146 Lisp_Object Qprocessp;
147 static Lisp_Object Qrun, Qstop, Qsignal;
148 static Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
149 Lisp_Object Qlocal;
150 static Lisp_Object Qipv4, Qdatagram, Qseqpacket;
151 static Lisp_Object Qreal, Qnetwork, Qserial;
152 #ifdef AF_INET6
153 static Lisp_Object Qipv6;
154 #endif
155 static Lisp_Object QCport, QCprocess;
156 Lisp_Object QCspeed;
157 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
158 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
159 static Lisp_Object QCbuffer, QChost, QCservice;
160 static Lisp_Object QClocal, QCremote, QCcoding;
161 static Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
162 static Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
163 static Lisp_Object Qlast_nonmenu_event;
164 /* QCfamily is declared and initialized in xfaces.c,
165 QCfilter in keyboard.c. */
166 extern Lisp_Object QCfamily, QCfilter;
167
168 /* Qexit is declared and initialized in eval.c. */
169
170 /* QCfamily is defined in xfaces.c. */
171 extern Lisp_Object QCfamily;
172 /* QCfilter is defined in keyboard.c. */
173 extern Lisp_Object QCfilter;
174
175 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
176 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
177 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
178 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
179
180 #ifndef HAVE_H_ERRNO
181 extern int h_errno;
182 #endif
183
184 /* Number of events of change of status of a process. */
185 static EMACS_INT process_tick;
186 /* Number of events for which the user or sentinel has been notified. */
187 static EMACS_INT update_tick;
188
189 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
190
191 /* Only W32 has this, it really means that select can't take write mask. */
192 #ifdef BROKEN_NON_BLOCKING_CONNECT
193 #undef NON_BLOCKING_CONNECT
194 #define SELECT_CANT_DO_WRITE_MASK
195 #else
196 #ifndef NON_BLOCKING_CONNECT
197 #ifdef HAVE_SELECT
198 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
199 #if defined (O_NONBLOCK) || defined (O_NDELAY)
200 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
201 #define NON_BLOCKING_CONNECT
202 #endif /* EWOULDBLOCK || EINPROGRESS */
203 #endif /* O_NONBLOCK || O_NDELAY */
204 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
205 #endif /* HAVE_SELECT */
206 #endif /* NON_BLOCKING_CONNECT */
207 #endif /* BROKEN_NON_BLOCKING_CONNECT */
208
209 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
210 this system. We need to read full packets, so we need a
211 "non-destructive" select. So we require either native select,
212 or emulation of select using FIONREAD. */
213
214 #ifdef BROKEN_DATAGRAM_SOCKETS
215 #undef DATAGRAM_SOCKETS
216 #else
217 #ifndef DATAGRAM_SOCKETS
218 #if defined (HAVE_SELECT) || defined (FIONREAD)
219 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
220 #define DATAGRAM_SOCKETS
221 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
222 #endif /* HAVE_SELECT || FIONREAD */
223 #endif /* DATAGRAM_SOCKETS */
224 #endif /* BROKEN_DATAGRAM_SOCKETS */
225
226 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
227 # define HAVE_SEQPACKET
228 #endif
229
230 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
231 #define ADAPTIVE_READ_BUFFERING
232 #endif
233
234 #ifdef ADAPTIVE_READ_BUFFERING
235 #define READ_OUTPUT_DELAY_INCREMENT (EMACS_TIME_RESOLUTION / 100)
236 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
237 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
238
239 /* Number of processes which have a non-zero read_output_delay,
240 and therefore might be delayed for adaptive read buffering. */
241
242 static int process_output_delay_count;
243
244 /* Non-zero if any process has non-nil read_output_skip. */
245
246 static int process_output_skip;
247
248 #else
249 #define process_output_delay_count 0
250 #endif
251
252 static Lisp_Object Fget_process (Lisp_Object);
253 static void create_process (Lisp_Object, char **, Lisp_Object);
254 #ifdef SIGIO
255 static int keyboard_bit_set (SELECT_TYPE *);
256 #endif
257 static void deactivate_process (Lisp_Object);
258 static void status_notify (struct Lisp_Process *);
259 static int read_process_output (Lisp_Object, int);
260 static void create_pty (Lisp_Object);
261
262 /* If we support a window system, turn on the code to poll periodically
263 to detect C-g. It isn't actually used when doing interrupt input. */
264 #if defined (HAVE_WINDOW_SYSTEM) && !defined (USE_ASYNC_EVENTS)
265 #define POLL_FOR_INPUT
266 #endif
267
268 static Lisp_Object get_process (register Lisp_Object name);
269 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
270
271 /* Mask of bits indicating the descriptors that we wait for input on. */
272
273 static SELECT_TYPE input_wait_mask;
274
275 /* Mask that excludes keyboard input descriptor(s). */
276
277 static SELECT_TYPE non_keyboard_wait_mask;
278
279 /* Mask that excludes process input descriptor(s). */
280
281 static SELECT_TYPE non_process_wait_mask;
282
283 /* Mask for selecting for write. */
284
285 static SELECT_TYPE write_mask;
286
287 #ifdef NON_BLOCKING_CONNECT
288 /* Mask of bits indicating the descriptors that we wait for connect to
289 complete on. Once they complete, they are removed from this mask
290 and added to the input_wait_mask and non_keyboard_wait_mask. */
291
292 static SELECT_TYPE connect_wait_mask;
293
294 /* Number of bits set in connect_wait_mask. */
295 static int num_pending_connects;
296 #endif /* NON_BLOCKING_CONNECT */
297
298 /* The largest descriptor currently in use for a process object. */
299 static int max_process_desc;
300
301 /* The largest descriptor currently in use for input. */
302 static int max_input_desc;
303
304 /* Indexed by descriptor, gives the process (if any) for that descriptor */
305 static Lisp_Object chan_process[MAXDESC];
306
307 /* Alist of elements (NAME . PROCESS) */
308 static Lisp_Object Vprocess_alist;
309
310 /* Buffered-ahead input char from process, indexed by channel.
311 -1 means empty (no char is buffered).
312 Used on sys V where the only way to tell if there is any
313 output from the process is to read at least one char.
314 Always -1 on systems that support FIONREAD. */
315
316 static int proc_buffered_char[MAXDESC];
317
318 /* Table of `struct coding-system' for each process. */
319 static struct coding_system *proc_decode_coding_system[MAXDESC];
320 static struct coding_system *proc_encode_coding_system[MAXDESC];
321
322 #ifdef DATAGRAM_SOCKETS
323 /* Table of `partner address' for datagram sockets. */
324 static struct sockaddr_and_len {
325 struct sockaddr *sa;
326 int len;
327 } datagram_address[MAXDESC];
328 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
329 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
330 #else
331 #define DATAGRAM_CHAN_P(chan) (0)
332 #define DATAGRAM_CONN_P(proc) (0)
333 #endif
334
335 /* Maximum number of bytes to send to a pty without an eof. */
336 static int pty_max_bytes;
337
338 \f
339
340 static struct fd_callback_data
341 {
342 fd_callback func;
343 void *data;
344 #define FOR_READ 1
345 #define FOR_WRITE 2
346 int condition; /* mask of the defines above. */
347 } fd_callback_info[MAXDESC];
348
349
350 /* Add a file descriptor FD to be monitored for when read is possible.
351 When read is possible, call FUNC with argument DATA. */
352
353 void
354 add_read_fd (int fd, fd_callback func, void *data)
355 {
356 eassert (fd < MAXDESC);
357 add_keyboard_wait_descriptor (fd);
358
359 fd_callback_info[fd].func = func;
360 fd_callback_info[fd].data = data;
361 fd_callback_info[fd].condition |= FOR_READ;
362 }
363
364 /* Stop monitoring file descriptor FD for when read is possible. */
365
366 void
367 delete_read_fd (int fd)
368 {
369 eassert (fd < MAXDESC);
370 delete_keyboard_wait_descriptor (fd);
371
372 fd_callback_info[fd].condition &= ~FOR_READ;
373 if (fd_callback_info[fd].condition == 0)
374 {
375 fd_callback_info[fd].func = 0;
376 fd_callback_info[fd].data = 0;
377 }
378 }
379
380 /* Add a file descriptor FD to be monitored for when write is possible.
381 When write is possible, call FUNC with argument DATA. */
382
383 void
384 add_write_fd (int fd, fd_callback func, void *data)
385 {
386 eassert (fd < MAXDESC);
387 FD_SET (fd, &write_mask);
388 if (fd > max_input_desc)
389 max_input_desc = fd;
390
391 fd_callback_info[fd].func = func;
392 fd_callback_info[fd].data = data;
393 fd_callback_info[fd].condition |= FOR_WRITE;
394 }
395
396 /* Stop monitoring file descriptor FD for when write is possible. */
397
398 void
399 delete_write_fd (int fd)
400 {
401 int lim = max_input_desc;
402
403 eassert (fd < MAXDESC);
404 FD_CLR (fd, &write_mask);
405 fd_callback_info[fd].condition &= ~FOR_WRITE;
406 if (fd_callback_info[fd].condition == 0)
407 {
408 fd_callback_info[fd].func = 0;
409 fd_callback_info[fd].data = 0;
410
411 if (fd == max_input_desc)
412 for (fd = lim; fd >= 0; fd--)
413 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
414 {
415 max_input_desc = fd;
416 break;
417 }
418
419 }
420 }
421
422 \f
423 /* Compute the Lisp form of the process status, p->status, from
424 the numeric status that was returned by `wait'. */
425
426 static Lisp_Object status_convert (int);
427
428 static void
429 update_status (struct Lisp_Process *p)
430 {
431 eassert (p->raw_status_new);
432 p->status = status_convert (p->raw_status);
433 p->raw_status_new = 0;
434 }
435
436 /* Convert a process status word in Unix format to
437 the list that we use internally. */
438
439 static Lisp_Object
440 status_convert (int w)
441 {
442 if (WIFSTOPPED (w))
443 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
444 else if (WIFEXITED (w))
445 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
446 WCOREDUMP (w) ? Qt : Qnil));
447 else if (WIFSIGNALED (w))
448 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
449 WCOREDUMP (w) ? Qt : Qnil));
450 else
451 return Qrun;
452 }
453
454 /* Given a status-list, extract the three pieces of information
455 and store them individually through the three pointers. */
456
457 static void
458 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
459 {
460 Lisp_Object tem;
461
462 if (SYMBOLP (l))
463 {
464 *symbol = l;
465 *code = 0;
466 *coredump = 0;
467 }
468 else
469 {
470 *symbol = XCAR (l);
471 tem = XCDR (l);
472 *code = XFASTINT (XCAR (tem));
473 tem = XCDR (tem);
474 *coredump = !NILP (tem);
475 }
476 }
477
478 /* Return a string describing a process status list. */
479
480 static Lisp_Object
481 status_message (struct Lisp_Process *p)
482 {
483 Lisp_Object status = p->status;
484 Lisp_Object symbol;
485 int code, coredump;
486 Lisp_Object string, string2;
487
488 decode_status (status, &symbol, &code, &coredump);
489
490 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
491 {
492 char *signame;
493 synchronize_system_messages_locale ();
494 signame = strsignal (code);
495 if (signame == 0)
496 string = build_string ("unknown");
497 else
498 {
499 int c1, c2;
500
501 string = make_unibyte_string (signame, strlen (signame));
502 if (! NILP (Vlocale_coding_system))
503 string = (code_convert_string_norecord
504 (string, Vlocale_coding_system, 0));
505 c1 = STRING_CHAR (SDATA (string));
506 c2 = downcase (c1);
507 if (c1 != c2)
508 Faset (string, make_number (0), make_number (c2));
509 }
510 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
511 return concat2 (string, string2);
512 }
513 else if (EQ (symbol, Qexit))
514 {
515 if (NETCONN1_P (p))
516 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
517 if (code == 0)
518 return build_string ("finished\n");
519 string = Fnumber_to_string (make_number (code));
520 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
521 return concat3 (build_string ("exited abnormally with code "),
522 string, string2);
523 }
524 else if (EQ (symbol, Qfailed))
525 {
526 string = Fnumber_to_string (make_number (code));
527 string2 = build_string ("\n");
528 return concat3 (build_string ("failed with code "),
529 string, string2);
530 }
531 else
532 return Fcopy_sequence (Fsymbol_name (symbol));
533 }
534 \f
535 #ifdef HAVE_PTYS
536
537 /* The file name of the pty opened by allocate_pty. */
538 static char pty_name[24];
539
540 /* Open an available pty, returning a file descriptor.
541 Return -1 on failure.
542 The file name of the terminal corresponding to the pty
543 is left in the variable pty_name. */
544
545 static int
546 allocate_pty (void)
547 {
548 int fd;
549
550 #ifdef PTY_ITERATION
551 PTY_ITERATION
552 #else
553 register int c, i;
554 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
555 for (i = 0; i < 16; i++)
556 #endif
557 {
558 #ifdef PTY_NAME_SPRINTF
559 PTY_NAME_SPRINTF
560 #else
561 sprintf (pty_name, "/dev/pty%c%x", c, i);
562 #endif /* no PTY_NAME_SPRINTF */
563
564 #ifdef PTY_OPEN
565 PTY_OPEN;
566 #else /* no PTY_OPEN */
567 {
568 { /* Some systems name their pseudoterminals so that there are gaps in
569 the usual sequence - for example, on HP9000/S700 systems, there
570 are no pseudoterminals with names ending in 'f'. So we wait for
571 three failures in a row before deciding that we've reached the
572 end of the ptys. */
573 int failed_count = 0;
574 struct stat stb;
575
576 if (stat (pty_name, &stb) < 0)
577 {
578 failed_count++;
579 if (failed_count >= 3)
580 return -1;
581 }
582 else
583 failed_count = 0;
584 }
585 # ifdef O_NONBLOCK
586 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
587 # else
588 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
589 # endif
590 }
591 #endif /* no PTY_OPEN */
592
593 if (fd >= 0)
594 {
595 /* check to make certain that both sides are available
596 this avoids a nasty yet stupid bug in rlogins */
597 #ifdef PTY_TTY_NAME_SPRINTF
598 PTY_TTY_NAME_SPRINTF
599 #else
600 sprintf (pty_name, "/dev/tty%c%x", c, i);
601 #endif /* no PTY_TTY_NAME_SPRINTF */
602 if (access (pty_name, 6) != 0)
603 {
604 emacs_close (fd);
605 # ifndef __sgi
606 continue;
607 # else
608 return -1;
609 # endif /* __sgi */
610 }
611 setup_pty (fd);
612 return fd;
613 }
614 }
615 return -1;
616 }
617 #endif /* HAVE_PTYS */
618 \f
619 static Lisp_Object
620 make_process (Lisp_Object name)
621 {
622 register Lisp_Object val, tem, name1;
623 register struct Lisp_Process *p;
624 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
625 printmax_t i;
626
627 p = allocate_process ();
628 /* Initialize Lisp data. Note that allocate_process initializes all
629 Lisp data to nil, so do it only for slots which should not be nil. */
630 p->status = Qrun;
631 p->mark = Fmake_marker ();
632
633 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
634 non-Lisp data, so do it only for slots which should not be zero. */
635 p->infd = -1;
636 p->outfd = -1;
637
638 #ifdef HAVE_GNUTLS
639 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
640 #endif
641
642 /* If name is already in use, modify it until it is unused. */
643
644 name1 = name;
645 for (i = 1; ; i++)
646 {
647 tem = Fget_process (name1);
648 if (NILP (tem)) break;
649 sprintf (suffix, "<%"pMd">", i);
650 name1 = concat2 (name, build_string (suffix));
651 }
652 name = name1;
653 p->name = name;
654 XSETPROCESS (val, p);
655 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
656 return val;
657 }
658
659 static void
660 remove_process (register Lisp_Object proc)
661 {
662 register Lisp_Object pair;
663
664 pair = Frassq (proc, Vprocess_alist);
665 Vprocess_alist = Fdelq (pair, Vprocess_alist);
666
667 deactivate_process (proc);
668 }
669
670 \f
671 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
672 doc: /* Return t if OBJECT is a process. */)
673 (Lisp_Object object)
674 {
675 return PROCESSP (object) ? Qt : Qnil;
676 }
677
678 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
679 doc: /* Return the process named NAME, or nil if there is none. */)
680 (register Lisp_Object name)
681 {
682 if (PROCESSP (name))
683 return name;
684 CHECK_STRING (name);
685 return Fcdr (Fassoc (name, Vprocess_alist));
686 }
687
688 /* This is how commands for the user decode process arguments. It
689 accepts a process, a process name, a buffer, a buffer name, or nil.
690 Buffers denote the first process in the buffer, and nil denotes the
691 current buffer. */
692
693 static Lisp_Object
694 get_process (register Lisp_Object name)
695 {
696 register Lisp_Object proc, obj;
697 if (STRINGP (name))
698 {
699 obj = Fget_process (name);
700 if (NILP (obj))
701 obj = Fget_buffer (name);
702 if (NILP (obj))
703 error ("Process %s does not exist", SDATA (name));
704 }
705 else if (NILP (name))
706 obj = Fcurrent_buffer ();
707 else
708 obj = name;
709
710 /* Now obj should be either a buffer object or a process object.
711 */
712 if (BUFFERP (obj))
713 {
714 proc = Fget_buffer_process (obj);
715 if (NILP (proc))
716 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
717 }
718 else
719 {
720 CHECK_PROCESS (obj);
721 proc = obj;
722 }
723 return proc;
724 }
725
726
727 #ifdef SIGCHLD
728 /* Fdelete_process promises to immediately forget about the process, but in
729 reality, Emacs needs to remember those processes until they have been
730 treated by sigchld_handler; otherwise this handler would consider the
731 process as being synchronous and say that the synchronous process is
732 dead. */
733 static Lisp_Object deleted_pid_list;
734 #endif
735
736 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
737 doc: /* Delete PROCESS: kill it and forget about it immediately.
738 PROCESS may be a process, a buffer, the name of a process or buffer, or
739 nil, indicating the current buffer's process. */)
740 (register Lisp_Object process)
741 {
742 register struct Lisp_Process *p;
743
744 process = get_process (process);
745 p = XPROCESS (process);
746
747 p->raw_status_new = 0;
748 if (NETCONN1_P (p) || SERIALCONN1_P (p))
749 {
750 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
751 p->tick = ++process_tick;
752 status_notify (p);
753 redisplay_preserve_echo_area (13);
754 }
755 else if (p->infd >= 0)
756 {
757 #ifdef SIGCHLD
758 Lisp_Object symbol;
759 pid_t pid = p->pid;
760
761 /* No problem storing the pid here, as it is still in Vprocess_alist. */
762 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
763 /* GC treated elements set to nil. */
764 Fdelq (Qnil, deleted_pid_list));
765 /* If the process has already signaled, remove it from the list. */
766 if (p->raw_status_new)
767 update_status (p);
768 symbol = p->status;
769 if (CONSP (p->status))
770 symbol = XCAR (p->status);
771 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
772 deleted_pid_list
773 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
774 else
775 #endif
776 {
777 Fkill_process (process, Qnil);
778 /* Do this now, since remove_process will make sigchld_handler do nothing. */
779 p->status
780 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
781 p->tick = ++process_tick;
782 status_notify (p);
783 redisplay_preserve_echo_area (13);
784 }
785 }
786 remove_process (process);
787 return Qnil;
788 }
789 \f
790 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
791 doc: /* Return the status of PROCESS.
792 The returned value is one of the following symbols:
793 run -- for a process that is running.
794 stop -- for a process stopped but continuable.
795 exit -- for a process that has exited.
796 signal -- for a process that has got a fatal signal.
797 open -- for a network stream connection that is open.
798 listen -- for a network stream server that is listening.
799 closed -- for a network stream connection that is closed.
800 connect -- when waiting for a non-blocking connection to complete.
801 failed -- when a non-blocking connection has failed.
802 nil -- if arg is a process name and no such process exists.
803 PROCESS may be a process, a buffer, the name of a process, or
804 nil, indicating the current buffer's process. */)
805 (register Lisp_Object process)
806 {
807 register struct Lisp_Process *p;
808 register Lisp_Object status;
809
810 if (STRINGP (process))
811 process = Fget_process (process);
812 else
813 process = get_process (process);
814
815 if (NILP (process))
816 return process;
817
818 p = XPROCESS (process);
819 if (p->raw_status_new)
820 update_status (p);
821 status = p->status;
822 if (CONSP (status))
823 status = XCAR (status);
824 if (NETCONN1_P (p) || SERIALCONN1_P (p))
825 {
826 if (EQ (status, Qexit))
827 status = Qclosed;
828 else if (EQ (p->command, Qt))
829 status = Qstop;
830 else if (EQ (status, Qrun))
831 status = Qopen;
832 }
833 return status;
834 }
835
836 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
837 1, 1, 0,
838 doc: /* Return the exit status of PROCESS or the signal number that killed it.
839 If PROCESS has not yet exited or died, return 0. */)
840 (register Lisp_Object process)
841 {
842 CHECK_PROCESS (process);
843 if (XPROCESS (process)->raw_status_new)
844 update_status (XPROCESS (process));
845 if (CONSP (XPROCESS (process)->status))
846 return XCAR (XCDR (XPROCESS (process)->status));
847 return make_number (0);
848 }
849
850 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
851 doc: /* Return the process id of PROCESS.
852 This is the pid of the external process which PROCESS uses or talks to.
853 For a network connection, this value is nil. */)
854 (register Lisp_Object process)
855 {
856 pid_t pid;
857
858 CHECK_PROCESS (process);
859 pid = XPROCESS (process)->pid;
860 return (pid ? make_fixnum_or_float (pid) : Qnil);
861 }
862
863 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
864 doc: /* Return the name of PROCESS, as a string.
865 This is the name of the program invoked in PROCESS,
866 possibly modified to make it unique among process names. */)
867 (register Lisp_Object process)
868 {
869 CHECK_PROCESS (process);
870 return XPROCESS (process)->name;
871 }
872
873 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
874 doc: /* Return the command that was executed to start PROCESS.
875 This is a list of strings, the first string being the program executed
876 and the rest of the strings being the arguments given to it.
877 For a network or serial process, this is nil (process is running) or t
878 \(process is stopped). */)
879 (register Lisp_Object process)
880 {
881 CHECK_PROCESS (process);
882 return XPROCESS (process)->command;
883 }
884
885 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
886 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
887 This is the terminal that the process itself reads and writes on,
888 not the name of the pty that Emacs uses to talk with that terminal. */)
889 (register Lisp_Object process)
890 {
891 CHECK_PROCESS (process);
892 return XPROCESS (process)->tty_name;
893 }
894
895 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
896 2, 2, 0,
897 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
898 Return BUFFER. */)
899 (register Lisp_Object process, Lisp_Object buffer)
900 {
901 struct Lisp_Process *p;
902
903 CHECK_PROCESS (process);
904 if (!NILP (buffer))
905 CHECK_BUFFER (buffer);
906 p = XPROCESS (process);
907 p->buffer = buffer;
908 if (NETCONN1_P (p) || SERIALCONN1_P (p))
909 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
910 setup_process_coding_systems (process);
911 return buffer;
912 }
913
914 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
915 1, 1, 0,
916 doc: /* Return the buffer PROCESS is associated with.
917 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
918 (register Lisp_Object process)
919 {
920 CHECK_PROCESS (process);
921 return XPROCESS (process)->buffer;
922 }
923
924 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
925 1, 1, 0,
926 doc: /* Return the marker for the end of the last output from PROCESS. */)
927 (register Lisp_Object process)
928 {
929 CHECK_PROCESS (process);
930 return XPROCESS (process)->mark;
931 }
932
933 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
934 2, 2, 0,
935 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
936 A value of t means stop accepting output from the process.
937
938 When a process has a filter, its buffer is not used for output.
939 Instead, each time it does output, the entire string of output is
940 passed to the filter.
941
942 The filter gets two arguments: the process and the string of output.
943 The string argument is normally a multibyte string, except:
944 - if the process' input coding system is no-conversion or raw-text,
945 it is a unibyte string (the non-converted input), or else
946 - if `default-enable-multibyte-characters' is nil, it is a unibyte
947 string (the result of converting the decoded input multibyte
948 string to unibyte with `string-make-unibyte'). */)
949 (register Lisp_Object process, Lisp_Object filter)
950 {
951 struct Lisp_Process *p;
952
953 CHECK_PROCESS (process);
954 p = XPROCESS (process);
955
956 /* Don't signal an error if the process' input file descriptor
957 is closed. This could make debugging Lisp more difficult,
958 for example when doing something like
959
960 (setq process (start-process ...))
961 (debug)
962 (set-process-filter process ...) */
963
964 if (p->infd >= 0)
965 {
966 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
967 {
968 FD_CLR (p->infd, &input_wait_mask);
969 FD_CLR (p->infd, &non_keyboard_wait_mask);
970 }
971 else if (EQ (p->filter, Qt)
972 /* Network or serial process not stopped: */
973 && !EQ (p->command, Qt))
974 {
975 FD_SET (p->infd, &input_wait_mask);
976 FD_SET (p->infd, &non_keyboard_wait_mask);
977 }
978 }
979
980 p->filter = filter;
981 if (NETCONN1_P (p) || SERIALCONN1_P (p))
982 p->childp = Fplist_put (p->childp, QCfilter, filter);
983 setup_process_coding_systems (process);
984 return filter;
985 }
986
987 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
988 1, 1, 0,
989 doc: /* Returns the filter function of PROCESS; nil if none.
990 See `set-process-filter' for more info on filter functions. */)
991 (register Lisp_Object process)
992 {
993 CHECK_PROCESS (process);
994 return XPROCESS (process)->filter;
995 }
996
997 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
998 2, 2, 0,
999 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1000 The sentinel is called as a function when the process changes state.
1001 It gets two arguments: the process, and a string describing the change. */)
1002 (register Lisp_Object process, Lisp_Object sentinel)
1003 {
1004 struct Lisp_Process *p;
1005
1006 CHECK_PROCESS (process);
1007 p = XPROCESS (process);
1008
1009 p->sentinel = sentinel;
1010 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1011 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
1012 return sentinel;
1013 }
1014
1015 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1016 1, 1, 0,
1017 doc: /* Return the sentinel of PROCESS; nil if none.
1018 See `set-process-sentinel' for more info on sentinels. */)
1019 (register Lisp_Object process)
1020 {
1021 CHECK_PROCESS (process);
1022 return XPROCESS (process)->sentinel;
1023 }
1024
1025 DEFUN ("set-process-window-size", Fset_process_window_size,
1026 Sset_process_window_size, 3, 3, 0,
1027 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1028 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
1029 {
1030 CHECK_PROCESS (process);
1031 CHECK_RANGED_INTEGER (0, height, INT_MAX);
1032 CHECK_RANGED_INTEGER (0, width, INT_MAX);
1033
1034 if (XPROCESS (process)->infd < 0
1035 || set_window_size (XPROCESS (process)->infd,
1036 XINT (height), XINT (width)) <= 0)
1037 return Qnil;
1038 else
1039 return Qt;
1040 }
1041
1042 DEFUN ("set-process-inherit-coding-system-flag",
1043 Fset_process_inherit_coding_system_flag,
1044 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1045 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1046 If the second argument FLAG is non-nil, then the variable
1047 `buffer-file-coding-system' of the buffer associated with PROCESS
1048 will be bound to the value of the coding system used to decode
1049 the process output.
1050
1051 This is useful when the coding system specified for the process buffer
1052 leaves either the character code conversion or the end-of-line conversion
1053 unspecified, or if the coding system used to decode the process output
1054 is more appropriate for saving the process buffer.
1055
1056 Binding the variable `inherit-process-coding-system' to non-nil before
1057 starting the process is an alternative way of setting the inherit flag
1058 for the process which will run.
1059
1060 This function returns FLAG. */)
1061 (register Lisp_Object process, Lisp_Object flag)
1062 {
1063 CHECK_PROCESS (process);
1064 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1065 return flag;
1066 }
1067
1068 DEFUN ("set-process-query-on-exit-flag",
1069 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1070 2, 2, 0,
1071 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1072 If the second argument FLAG is non-nil, Emacs will query the user before
1073 exiting or killing a buffer if PROCESS is running. This function
1074 returns FLAG. */)
1075 (register Lisp_Object process, Lisp_Object flag)
1076 {
1077 CHECK_PROCESS (process);
1078 XPROCESS (process)->kill_without_query = NILP (flag);
1079 return flag;
1080 }
1081
1082 DEFUN ("process-query-on-exit-flag",
1083 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1084 1, 1, 0,
1085 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1086 (register Lisp_Object process)
1087 {
1088 CHECK_PROCESS (process);
1089 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1090 }
1091
1092 #ifdef DATAGRAM_SOCKETS
1093 static Lisp_Object Fprocess_datagram_address (Lisp_Object);
1094 #endif
1095
1096 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1097 1, 2, 0,
1098 doc: /* Return the contact info of PROCESS; t for a real child.
1099 For a network or serial connection, the value depends on the optional
1100 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1101 SERVICE) for a network connection or (PORT SPEED) for a serial
1102 connection. If KEY is t, the complete contact information for the
1103 connection is returned, else the specific value for the keyword KEY is
1104 returned. See `make-network-process' or `make-serial-process' for a
1105 list of keywords. */)
1106 (register Lisp_Object process, Lisp_Object key)
1107 {
1108 Lisp_Object contact;
1109
1110 CHECK_PROCESS (process);
1111 contact = XPROCESS (process)->childp;
1112
1113 #ifdef DATAGRAM_SOCKETS
1114 if (DATAGRAM_CONN_P (process)
1115 && (EQ (key, Qt) || EQ (key, QCremote)))
1116 contact = Fplist_put (contact, QCremote,
1117 Fprocess_datagram_address (process));
1118 #endif
1119
1120 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1121 return contact;
1122 if (NILP (key) && NETCONN_P (process))
1123 return Fcons (Fplist_get (contact, QChost),
1124 Fcons (Fplist_get (contact, QCservice), Qnil));
1125 if (NILP (key) && SERIALCONN_P (process))
1126 return Fcons (Fplist_get (contact, QCport),
1127 Fcons (Fplist_get (contact, QCspeed), Qnil));
1128 return Fplist_get (contact, key);
1129 }
1130
1131 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1132 1, 1, 0,
1133 doc: /* Return the plist of PROCESS. */)
1134 (register Lisp_Object process)
1135 {
1136 CHECK_PROCESS (process);
1137 return XPROCESS (process)->plist;
1138 }
1139
1140 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1141 2, 2, 0,
1142 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1143 (register Lisp_Object process, Lisp_Object plist)
1144 {
1145 CHECK_PROCESS (process);
1146 CHECK_LIST (plist);
1147
1148 XPROCESS (process)->plist = plist;
1149 return plist;
1150 }
1151
1152 #if 0 /* Turned off because we don't currently record this info
1153 in the process. Perhaps add it. */
1154 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1155 doc: /* Return the connection type of PROCESS.
1156 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1157 a socket connection. */)
1158 (Lisp_Object process)
1159 {
1160 return XPROCESS (process)->type;
1161 }
1162 #endif
1163
1164 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1165 doc: /* Return the connection type of PROCESS.
1166 The value is either the symbol `real', `network', or `serial'.
1167 PROCESS may be a process, a buffer, the name of a process or buffer, or
1168 nil, indicating the current buffer's process. */)
1169 (Lisp_Object process)
1170 {
1171 Lisp_Object proc;
1172 proc = get_process (process);
1173 return XPROCESS (proc)->type;
1174 }
1175
1176 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1177 1, 2, 0,
1178 doc: /* Convert network ADDRESS from internal format to a string.
1179 A 4 or 5 element vector represents an IPv4 address (with port number).
1180 An 8 or 9 element vector represents an IPv6 address (with port number).
1181 If optional second argument OMIT-PORT is non-nil, don't include a port
1182 number in the string, even when present in ADDRESS.
1183 Returns nil if format of ADDRESS is invalid. */)
1184 (Lisp_Object address, Lisp_Object omit_port)
1185 {
1186 if (NILP (address))
1187 return Qnil;
1188
1189 if (STRINGP (address)) /* AF_LOCAL */
1190 return address;
1191
1192 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1193 {
1194 register struct Lisp_Vector *p = XVECTOR (address);
1195 ptrdiff_t size = p->header.size;
1196 Lisp_Object args[10];
1197 int nargs, i;
1198
1199 if (size == 4 || (size == 5 && !NILP (omit_port)))
1200 {
1201 args[0] = build_string ("%d.%d.%d.%d");
1202 nargs = 4;
1203 }
1204 else if (size == 5)
1205 {
1206 args[0] = build_string ("%d.%d.%d.%d:%d");
1207 nargs = 5;
1208 }
1209 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1210 {
1211 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1212 nargs = 8;
1213 }
1214 else if (size == 9)
1215 {
1216 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1217 nargs = 9;
1218 }
1219 else
1220 return Qnil;
1221
1222 for (i = 0; i < nargs; i++)
1223 {
1224 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1225 return Qnil;
1226
1227 if (nargs <= 5 /* IPv4 */
1228 && i < 4 /* host, not port */
1229 && XINT (p->contents[i]) > 255)
1230 return Qnil;
1231
1232 args[i+1] = p->contents[i];
1233 }
1234
1235 return Fformat (nargs+1, args);
1236 }
1237
1238 if (CONSP (address))
1239 {
1240 Lisp_Object args[2];
1241 args[0] = build_string ("<Family %d>");
1242 args[1] = Fcar (address);
1243 return Fformat (2, args);
1244 }
1245
1246 return Qnil;
1247 }
1248
1249 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1250 doc: /* Return a list of all processes. */)
1251 (void)
1252 {
1253 return Fmapcar (Qcdr, Vprocess_alist);
1254 }
1255 \f
1256 /* Starting asynchronous inferior processes. */
1257
1258 static Lisp_Object start_process_unwind (Lisp_Object proc);
1259
1260 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1261 doc: /* Start a program in a subprocess. Return the process object for it.
1262 NAME is name for process. It is modified if necessary to make it unique.
1263 BUFFER is the buffer (or buffer name) to associate with the process.
1264
1265 Process output (both standard output and standard error streams) goes
1266 at end of BUFFER, unless you specify an output stream or filter
1267 function to handle the output. BUFFER may also be nil, meaning that
1268 this process is not associated with any buffer.
1269
1270 PROGRAM is the program file name. It is searched for in `exec-path'
1271 (which see). If nil, just associate a pty with the buffer. Remaining
1272 arguments are strings to give program as arguments.
1273
1274 If you want to separate standard output from standard error, invoke
1275 the command through a shell and redirect one of them using the shell
1276 syntax.
1277
1278 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1279 (ptrdiff_t nargs, Lisp_Object *args)
1280 {
1281 Lisp_Object buffer, name, program, proc, current_dir, tem;
1282 register unsigned char **new_argv;
1283 ptrdiff_t i;
1284 ptrdiff_t count = SPECPDL_INDEX ();
1285
1286 buffer = args[1];
1287 if (!NILP (buffer))
1288 buffer = Fget_buffer_create (buffer);
1289
1290 /* Make sure that the child will be able to chdir to the current
1291 buffer's current directory, or its unhandled equivalent. We
1292 can't just have the child check for an error when it does the
1293 chdir, since it's in a vfork.
1294
1295 We have to GCPRO around this because Fexpand_file_name and
1296 Funhandled_file_name_directory might call a file name handling
1297 function. The argument list is protected by the caller, so all
1298 we really have to worry about is buffer. */
1299 {
1300 struct gcpro gcpro1, gcpro2;
1301
1302 current_dir = BVAR (current_buffer, directory);
1303
1304 GCPRO2 (buffer, current_dir);
1305
1306 current_dir = Funhandled_file_name_directory (current_dir);
1307 if (NILP (current_dir))
1308 /* If the file name handler says that current_dir is unreachable, use
1309 a sensible default. */
1310 current_dir = build_string ("~/");
1311 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1312 if (NILP (Ffile_accessible_directory_p (current_dir)))
1313 report_file_error ("Setting current directory",
1314 Fcons (BVAR (current_buffer, directory), Qnil));
1315
1316 UNGCPRO;
1317 }
1318
1319 name = args[0];
1320 CHECK_STRING (name);
1321
1322 program = args[2];
1323
1324 if (!NILP (program))
1325 CHECK_STRING (program);
1326
1327 proc = make_process (name);
1328 /* If an error occurs and we can't start the process, we want to
1329 remove it from the process list. This means that each error
1330 check in create_process doesn't need to call remove_process
1331 itself; it's all taken care of here. */
1332 record_unwind_protect (start_process_unwind, proc);
1333
1334 XPROCESS (proc)->childp = Qt;
1335 XPROCESS (proc)->plist = Qnil;
1336 XPROCESS (proc)->type = Qreal;
1337 XPROCESS (proc)->buffer = buffer;
1338 XPROCESS (proc)->sentinel = Qnil;
1339 XPROCESS (proc)->filter = Qnil;
1340 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1341
1342 #ifdef HAVE_GNUTLS
1343 /* AKA GNUTLS_INITSTAGE(proc). */
1344 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1345 XPROCESS (proc)->gnutls_cred_type = Qnil;
1346 #endif
1347
1348 #ifdef ADAPTIVE_READ_BUFFERING
1349 XPROCESS (proc)->adaptive_read_buffering
1350 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1351 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1352 #endif
1353
1354 /* Make the process marker point into the process buffer (if any). */
1355 if (BUFFERP (buffer))
1356 set_marker_both (XPROCESS (proc)->mark, buffer,
1357 BUF_ZV (XBUFFER (buffer)),
1358 BUF_ZV_BYTE (XBUFFER (buffer)));
1359
1360 {
1361 /* Decide coding systems for communicating with the process. Here
1362 we don't setup the structure coding_system nor pay attention to
1363 unibyte mode. They are done in create_process. */
1364
1365 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1366 Lisp_Object coding_systems = Qt;
1367 Lisp_Object val, *args2;
1368 struct gcpro gcpro1, gcpro2;
1369
1370 val = Vcoding_system_for_read;
1371 if (NILP (val))
1372 {
1373 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1374 args2[0] = Qstart_process;
1375 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1376 GCPRO2 (proc, current_dir);
1377 if (!NILP (program))
1378 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1379 UNGCPRO;
1380 if (CONSP (coding_systems))
1381 val = XCAR (coding_systems);
1382 else if (CONSP (Vdefault_process_coding_system))
1383 val = XCAR (Vdefault_process_coding_system);
1384 }
1385 XPROCESS (proc)->decode_coding_system = val;
1386
1387 val = Vcoding_system_for_write;
1388 if (NILP (val))
1389 {
1390 if (EQ (coding_systems, Qt))
1391 {
1392 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1393 args2[0] = Qstart_process;
1394 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1395 GCPRO2 (proc, current_dir);
1396 if (!NILP (program))
1397 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1398 UNGCPRO;
1399 }
1400 if (CONSP (coding_systems))
1401 val = XCDR (coding_systems);
1402 else if (CONSP (Vdefault_process_coding_system))
1403 val = XCDR (Vdefault_process_coding_system);
1404 }
1405 XPROCESS (proc)->encode_coding_system = val;
1406 /* Note: At this moment, the above coding system may leave
1407 text-conversion or eol-conversion unspecified. They will be
1408 decided after we read output from the process and decode it by
1409 some coding system, or just before we actually send a text to
1410 the process. */
1411 }
1412
1413
1414 XPROCESS (proc)->decoding_buf = empty_unibyte_string;
1415 XPROCESS (proc)->decoding_carryover = 0;
1416 XPROCESS (proc)->encoding_buf = empty_unibyte_string;
1417
1418 XPROCESS (proc)->inherit_coding_system_flag
1419 = !(NILP (buffer) || !inherit_process_coding_system);
1420
1421 if (!NILP (program))
1422 {
1423 /* If program file name is not absolute, search our path for it.
1424 Put the name we will really use in TEM. */
1425 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1426 && !(SCHARS (program) > 1
1427 && IS_DEVICE_SEP (SREF (program, 1))))
1428 {
1429 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1430
1431 tem = Qnil;
1432 GCPRO4 (name, program, buffer, current_dir);
1433 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1434 UNGCPRO;
1435 if (NILP (tem))
1436 report_file_error ("Searching for program", Fcons (program, Qnil));
1437 tem = Fexpand_file_name (tem, Qnil);
1438 }
1439 else
1440 {
1441 if (!NILP (Ffile_directory_p (program)))
1442 error ("Specified program for new process is a directory");
1443 tem = program;
1444 }
1445
1446 /* If program file name starts with /: for quoting a magic name,
1447 discard that. */
1448 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1449 && SREF (tem, 1) == ':')
1450 tem = Fsubstring (tem, make_number (2), Qnil);
1451
1452 {
1453 Lisp_Object arg_encoding = Qnil;
1454 struct gcpro gcpro1;
1455 GCPRO1 (tem);
1456
1457 /* Encode the file name and put it in NEW_ARGV.
1458 That's where the child will use it to execute the program. */
1459 tem = Fcons (ENCODE_FILE (tem), Qnil);
1460
1461 /* Here we encode arguments by the coding system used for sending
1462 data to the process. We don't support using different coding
1463 systems for encoding arguments and for encoding data sent to the
1464 process. */
1465
1466 for (i = 3; i < nargs; i++)
1467 {
1468 tem = Fcons (args[i], tem);
1469 CHECK_STRING (XCAR (tem));
1470 if (STRING_MULTIBYTE (XCAR (tem)))
1471 {
1472 if (NILP (arg_encoding))
1473 arg_encoding = (complement_process_encoding_system
1474 (XPROCESS (proc)->encode_coding_system));
1475 XSETCAR (tem,
1476 code_convert_string_norecord
1477 (XCAR (tem), arg_encoding, 1));
1478 }
1479 }
1480
1481 UNGCPRO;
1482 }
1483
1484 /* Now that everything is encoded we can collect the strings into
1485 NEW_ARGV. */
1486 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1487 new_argv[nargs - 2] = 0;
1488
1489 for (i = nargs - 2; i-- != 0; )
1490 {
1491 new_argv[i] = SDATA (XCAR (tem));
1492 tem = XCDR (tem);
1493 }
1494
1495 create_process (proc, (char **) new_argv, current_dir);
1496 }
1497 else
1498 create_pty (proc);
1499
1500 return unbind_to (count, proc);
1501 }
1502
1503 /* This function is the unwind_protect form for Fstart_process. If
1504 PROC doesn't have its pid set, then we know someone has signaled
1505 an error and the process wasn't started successfully, so we should
1506 remove it from the process list. */
1507 static Lisp_Object
1508 start_process_unwind (Lisp_Object proc)
1509 {
1510 if (!PROCESSP (proc))
1511 abort ();
1512
1513 /* Was PROC started successfully?
1514 -2 is used for a pty with no process, eg for gdb. */
1515 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1516 remove_process (proc);
1517
1518 return Qnil;
1519 }
1520
1521 static void
1522 create_process_1 (struct atimer *timer)
1523 {
1524 /* Nothing to do. */
1525 }
1526
1527
1528 static void
1529 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1530 {
1531 int inchannel, outchannel;
1532 pid_t pid;
1533 int sv[2];
1534 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1535 int wait_child_setup[2];
1536 #endif
1537 sigset_t procmask;
1538 sigset_t blocked;
1539 struct sigaction sigint_action;
1540 struct sigaction sigquit_action;
1541 struct sigaction sigpipe_action;
1542 #ifdef AIX
1543 struct sigaction sighup_action;
1544 #endif
1545 /* Use volatile to protect variables from being clobbered by longjmp. */
1546 volatile int forkin, forkout;
1547 volatile int pty_flag = 0;
1548 #ifndef USE_CRT_DLL
1549 extern char **environ;
1550 #endif
1551
1552 inchannel = outchannel = -1;
1553
1554 #ifdef HAVE_PTYS
1555 if (!NILP (Vprocess_connection_type))
1556 outchannel = inchannel = allocate_pty ();
1557
1558 if (inchannel >= 0)
1559 {
1560 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1561 /* On most USG systems it does not work to open the pty's tty here,
1562 then close it and reopen it in the child. */
1563 #ifdef O_NOCTTY
1564 /* Don't let this terminal become our controlling terminal
1565 (in case we don't have one). */
1566 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1567 #else
1568 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1569 #endif
1570 if (forkin < 0)
1571 report_file_error ("Opening pty", Qnil);
1572 #else
1573 forkin = forkout = -1;
1574 #endif /* not USG, or USG_SUBTTY_WORKS */
1575 pty_flag = 1;
1576 }
1577 else
1578 #endif /* HAVE_PTYS */
1579 {
1580 int tem;
1581 tem = pipe (sv);
1582 if (tem < 0)
1583 report_file_error ("Creating pipe", Qnil);
1584 inchannel = sv[0];
1585 forkout = sv[1];
1586 tem = pipe (sv);
1587 if (tem < 0)
1588 {
1589 emacs_close (inchannel);
1590 emacs_close (forkout);
1591 report_file_error ("Creating pipe", Qnil);
1592 }
1593 outchannel = sv[1];
1594 forkin = sv[0];
1595 }
1596
1597 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1598 {
1599 int tem;
1600
1601 tem = pipe (wait_child_setup);
1602 if (tem < 0)
1603 report_file_error ("Creating pipe", Qnil);
1604 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1605 if (tem >= 0)
1606 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1607 if (tem < 0)
1608 {
1609 emacs_close (wait_child_setup[0]);
1610 emacs_close (wait_child_setup[1]);
1611 report_file_error ("Setting file descriptor flags", Qnil);
1612 }
1613 }
1614 #endif
1615
1616 #ifdef O_NONBLOCK
1617 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1618 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1619 #else
1620 #ifdef O_NDELAY
1621 fcntl (inchannel, F_SETFL, O_NDELAY);
1622 fcntl (outchannel, F_SETFL, O_NDELAY);
1623 #endif
1624 #endif
1625
1626 /* Record this as an active process, with its channels.
1627 As a result, child_setup will close Emacs's side of the pipes. */
1628 chan_process[inchannel] = process;
1629 XPROCESS (process)->infd = inchannel;
1630 XPROCESS (process)->outfd = outchannel;
1631
1632 /* Previously we recorded the tty descriptor used in the subprocess.
1633 It was only used for getting the foreground tty process, so now
1634 we just reopen the device (see emacs_get_tty_pgrp) as this is
1635 more portable (see USG_SUBTTY_WORKS above). */
1636
1637 XPROCESS (process)->pty_flag = pty_flag;
1638 XPROCESS (process)->status = Qrun;
1639
1640 /* Delay interrupts until we have a chance to store
1641 the new fork's pid in its process structure */
1642 sigemptyset (&blocked);
1643 #ifdef SIGCHLD
1644 sigaddset (&blocked, SIGCHLD);
1645 #endif
1646 #ifdef HAVE_WORKING_VFORK
1647 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1648 this sets the parent's signal handlers as well as the child's.
1649 So delay all interrupts whose handlers the child might munge,
1650 and record the current handlers so they can be restored later. */
1651 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1652 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1653 sigaddset (&blocked, SIGPIPE); sigaction (SIGPIPE, 0, &sigpipe_action);
1654 #ifdef AIX
1655 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1656 #endif
1657 #endif /* HAVE_WORKING_VFORK */
1658 pthread_sigmask (SIG_BLOCK, &blocked, &procmask);
1659
1660 FD_SET (inchannel, &input_wait_mask);
1661 FD_SET (inchannel, &non_keyboard_wait_mask);
1662 if (inchannel > max_process_desc)
1663 max_process_desc = inchannel;
1664
1665 /* Until we store the proper pid, enable sigchld_handler
1666 to recognize an unknown pid as standing for this process.
1667 It is very important not to let this `marker' value stay
1668 in the table after this function has returned; if it does
1669 it might cause call-process to hang and subsequent asynchronous
1670 processes to get their return values scrambled. */
1671 XPROCESS (process)->pid = -1;
1672
1673 /* This must be called after the above line because it may signal an
1674 error. */
1675 setup_process_coding_systems (process);
1676
1677 BLOCK_INPUT;
1678
1679 {
1680 /* child_setup must clobber environ on systems with true vfork.
1681 Protect it from permanent change. */
1682 char **save_environ = environ;
1683 volatile Lisp_Object encoded_current_dir = ENCODE_FILE (current_dir);
1684
1685 #ifndef WINDOWSNT
1686 pid = vfork ();
1687 if (pid == 0)
1688 #endif /* not WINDOWSNT */
1689 {
1690 int xforkin = forkin;
1691 int xforkout = forkout;
1692
1693 #if 0 /* This was probably a mistake--it duplicates code later on,
1694 but fails to handle all the cases. */
1695 /* Make sure SIGCHLD is not blocked in the child. */
1696 sigsetmask (SIGEMPTYMASK);
1697 #endif
1698
1699 /* Make the pty be the controlling terminal of the process. */
1700 #ifdef HAVE_PTYS
1701 /* First, disconnect its current controlling terminal. */
1702 #ifdef HAVE_SETSID
1703 /* We tried doing setsid only if pty_flag, but it caused
1704 process_set_signal to fail on SGI when using a pipe. */
1705 setsid ();
1706 /* Make the pty's terminal the controlling terminal. */
1707 if (pty_flag && xforkin >= 0)
1708 {
1709 #ifdef TIOCSCTTY
1710 /* We ignore the return value
1711 because faith@cs.unc.edu says that is necessary on Linux. */
1712 ioctl (xforkin, TIOCSCTTY, 0);
1713 #endif
1714 }
1715 #else /* not HAVE_SETSID */
1716 #ifdef USG
1717 /* It's very important to call setpgrp here and no time
1718 afterwards. Otherwise, we lose our controlling tty which
1719 is set when we open the pty. */
1720 setpgrp ();
1721 #endif /* USG */
1722 #endif /* not HAVE_SETSID */
1723 #if defined (LDISC1)
1724 if (pty_flag && xforkin >= 0)
1725 {
1726 struct termios t;
1727 tcgetattr (xforkin, &t);
1728 t.c_lflag = LDISC1;
1729 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1730 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1731 }
1732 #else
1733 #if defined (NTTYDISC) && defined (TIOCSETD)
1734 if (pty_flag && xforkin >= 0)
1735 {
1736 /* Use new line discipline. */
1737 int ldisc = NTTYDISC;
1738 ioctl (xforkin, TIOCSETD, &ldisc);
1739 }
1740 #endif
1741 #endif
1742 #ifdef TIOCNOTTY
1743 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1744 can do TIOCSPGRP only to the process's controlling tty. */
1745 if (pty_flag)
1746 {
1747 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1748 I can't test it since I don't have 4.3. */
1749 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1750 if (j >= 0)
1751 {
1752 ioctl (j, TIOCNOTTY, 0);
1753 emacs_close (j);
1754 }
1755 #ifndef USG
1756 /* In order to get a controlling terminal on some versions
1757 of BSD, it is necessary to put the process in pgrp 0
1758 before it opens the terminal. */
1759 #ifdef HAVE_SETPGID
1760 setpgid (0, 0);
1761 #else
1762 setpgrp (0, 0);
1763 #endif
1764 #endif
1765 }
1766 #endif /* TIOCNOTTY */
1767
1768 #if !defined (DONT_REOPEN_PTY)
1769 /*** There is a suggestion that this ought to be a
1770 conditional on TIOCSPGRP,
1771 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
1772 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1773 that system does seem to need this code, even though
1774 both HAVE_SETSID and TIOCSCTTY are defined. */
1775 /* Now close the pty (if we had it open) and reopen it.
1776 This makes the pty the controlling terminal of the subprocess. */
1777 if (pty_flag)
1778 {
1779
1780 /* I wonder if emacs_close (emacs_open (pty_name, ...))
1781 would work? */
1782 if (xforkin >= 0)
1783 emacs_close (xforkin);
1784 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
1785
1786 if (xforkin < 0)
1787 {
1788 emacs_write (1, "Couldn't open the pty terminal ", 31);
1789 emacs_write (1, pty_name, strlen (pty_name));
1790 emacs_write (1, "\n", 1);
1791 _exit (1);
1792 }
1793
1794 }
1795 #endif /* not DONT_REOPEN_PTY */
1796
1797 #ifdef SETUP_SLAVE_PTY
1798 if (pty_flag)
1799 {
1800 SETUP_SLAVE_PTY;
1801 }
1802 #endif /* SETUP_SLAVE_PTY */
1803 #ifdef AIX
1804 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1805 Now reenable it in the child, so it will die when we want it to. */
1806 if (pty_flag)
1807 signal (SIGHUP, SIG_DFL);
1808 #endif
1809 #endif /* HAVE_PTYS */
1810
1811 signal (SIGINT, SIG_DFL);
1812 signal (SIGQUIT, SIG_DFL);
1813 /* GConf causes us to ignore SIGPIPE, make sure it is restored
1814 in the child. */
1815 signal (SIGPIPE, SIG_DFL);
1816
1817 /* Stop blocking signals in the child. */
1818 pthread_sigmask (SIG_SETMASK, &procmask, 0);
1819
1820 if (pty_flag)
1821 child_setup_tty (xforkout);
1822 #ifdef WINDOWSNT
1823 pid = child_setup (xforkin, xforkout, xforkout,
1824 new_argv, 1, encoded_current_dir);
1825 #else /* not WINDOWSNT */
1826 #ifdef FD_CLOEXEC
1827 emacs_close (wait_child_setup[0]);
1828 #endif
1829 child_setup (xforkin, xforkout, xforkout,
1830 new_argv, 1, encoded_current_dir);
1831 #endif /* not WINDOWSNT */
1832 }
1833 environ = save_environ;
1834 }
1835
1836 UNBLOCK_INPUT;
1837
1838 /* This runs in the Emacs process. */
1839 if (pid < 0)
1840 {
1841 if (forkin >= 0)
1842 emacs_close (forkin);
1843 if (forkin != forkout && forkout >= 0)
1844 emacs_close (forkout);
1845 }
1846 else
1847 {
1848 /* vfork succeeded. */
1849 XPROCESS (process)->pid = pid;
1850
1851 #ifdef WINDOWSNT
1852 register_child (pid, inchannel);
1853 #endif /* WINDOWSNT */
1854
1855 /* If the subfork execv fails, and it exits,
1856 this close hangs. I don't know why.
1857 So have an interrupt jar it loose. */
1858 {
1859 struct atimer *timer;
1860 EMACS_TIME offset;
1861
1862 stop_polling ();
1863 EMACS_SET_SECS_USECS (offset, 1, 0);
1864 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
1865
1866 if (forkin >= 0)
1867 emacs_close (forkin);
1868
1869 cancel_atimer (timer);
1870 start_polling ();
1871 }
1872
1873 if (forkin != forkout && forkout >= 0)
1874 emacs_close (forkout);
1875
1876 #ifdef HAVE_PTYS
1877 if (pty_flag)
1878 XPROCESS (process)->tty_name = build_string (pty_name);
1879 else
1880 #endif
1881 XPROCESS (process)->tty_name = Qnil;
1882
1883 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1884 /* Wait for child_setup to complete in case that vfork is
1885 actually defined as fork. The descriptor wait_child_setup[1]
1886 of a pipe is closed at the child side either by close-on-exec
1887 on successful execvp or the _exit call in child_setup. */
1888 {
1889 char dummy;
1890
1891 emacs_close (wait_child_setup[1]);
1892 emacs_read (wait_child_setup[0], &dummy, 1);
1893 emacs_close (wait_child_setup[0]);
1894 }
1895 #endif
1896 }
1897
1898 /* Restore the signal state whether vfork succeeded or not.
1899 (We will signal an error, below, if it failed.) */
1900 #ifdef HAVE_WORKING_VFORK
1901 /* Restore the parent's signal handlers. */
1902 sigaction (SIGINT, &sigint_action, 0);
1903 sigaction (SIGQUIT, &sigquit_action, 0);
1904 sigaction (SIGPIPE, &sigpipe_action, 0);
1905 #ifdef AIX
1906 sigaction (SIGHUP, &sighup_action, 0);
1907 #endif
1908 #endif /* HAVE_WORKING_VFORK */
1909 /* Stop blocking signals in the parent. */
1910 pthread_sigmask (SIG_SETMASK, &procmask, 0);
1911
1912 /* Now generate the error if vfork failed. */
1913 if (pid < 0)
1914 report_file_error ("Doing vfork", Qnil);
1915 }
1916
1917 void
1918 create_pty (Lisp_Object process)
1919 {
1920 int inchannel, outchannel;
1921 int pty_flag = 0;
1922
1923 inchannel = outchannel = -1;
1924
1925 #ifdef HAVE_PTYS
1926 if (!NILP (Vprocess_connection_type))
1927 outchannel = inchannel = allocate_pty ();
1928
1929 if (inchannel >= 0)
1930 {
1931 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1932 /* On most USG systems it does not work to open the pty's tty here,
1933 then close it and reopen it in the child. */
1934 #ifdef O_NOCTTY
1935 /* Don't let this terminal become our controlling terminal
1936 (in case we don't have one). */
1937 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1938 #else
1939 int forkout = emacs_open (pty_name, O_RDWR, 0);
1940 #endif
1941 if (forkout < 0)
1942 report_file_error ("Opening pty", Qnil);
1943 #if defined (DONT_REOPEN_PTY)
1944 /* In the case that vfork is defined as fork, the parent process
1945 (Emacs) may send some data before the child process completes
1946 tty options setup. So we setup tty before forking. */
1947 child_setup_tty (forkout);
1948 #endif /* DONT_REOPEN_PTY */
1949 #endif /* not USG, or USG_SUBTTY_WORKS */
1950 pty_flag = 1;
1951 }
1952 #endif /* HAVE_PTYS */
1953
1954 #ifdef O_NONBLOCK
1955 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1956 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1957 #else
1958 #ifdef O_NDELAY
1959 fcntl (inchannel, F_SETFL, O_NDELAY);
1960 fcntl (outchannel, F_SETFL, O_NDELAY);
1961 #endif
1962 #endif
1963
1964 /* Record this as an active process, with its channels.
1965 As a result, child_setup will close Emacs's side of the pipes. */
1966 chan_process[inchannel] = process;
1967 XPROCESS (process)->infd = inchannel;
1968 XPROCESS (process)->outfd = outchannel;
1969
1970 /* Previously we recorded the tty descriptor used in the subprocess.
1971 It was only used for getting the foreground tty process, so now
1972 we just reopen the device (see emacs_get_tty_pgrp) as this is
1973 more portable (see USG_SUBTTY_WORKS above). */
1974
1975 XPROCESS (process)->pty_flag = pty_flag;
1976 XPROCESS (process)->status = Qrun;
1977 setup_process_coding_systems (process);
1978
1979 FD_SET (inchannel, &input_wait_mask);
1980 FD_SET (inchannel, &non_keyboard_wait_mask);
1981 if (inchannel > max_process_desc)
1982 max_process_desc = inchannel;
1983
1984 XPROCESS (process)->pid = -2;
1985 #ifdef HAVE_PTYS
1986 if (pty_flag)
1987 XPROCESS (process)->tty_name = build_string (pty_name);
1988 else
1989 #endif
1990 XPROCESS (process)->tty_name = Qnil;
1991 }
1992
1993 \f
1994 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1995 The address family of sa is not included in the result. */
1996
1997 static Lisp_Object
1998 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
1999 {
2000 Lisp_Object address;
2001 int i;
2002 unsigned char *cp;
2003 register struct Lisp_Vector *p;
2004
2005 /* Workaround for a bug in getsockname on BSD: Names bound to
2006 sockets in the UNIX domain are inaccessible; getsockname returns
2007 a zero length name. */
2008 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2009 return empty_unibyte_string;
2010
2011 switch (sa->sa_family)
2012 {
2013 case AF_INET:
2014 {
2015 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2016 len = sizeof (sin->sin_addr) + 1;
2017 address = Fmake_vector (make_number (len), Qnil);
2018 p = XVECTOR (address);
2019 p->contents[--len] = make_number (ntohs (sin->sin_port));
2020 cp = (unsigned char *) &sin->sin_addr;
2021 break;
2022 }
2023 #ifdef AF_INET6
2024 case AF_INET6:
2025 {
2026 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2027 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2028 len = sizeof (sin6->sin6_addr)/2 + 1;
2029 address = Fmake_vector (make_number (len), Qnil);
2030 p = XVECTOR (address);
2031 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2032 for (i = 0; i < len; i++)
2033 p->contents[i] = make_number (ntohs (ip6[i]));
2034 return address;
2035 }
2036 #endif
2037 #ifdef HAVE_LOCAL_SOCKETS
2038 case AF_LOCAL:
2039 {
2040 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2041 for (i = 0; i < sizeof (sockun->sun_path); i++)
2042 if (sockun->sun_path[i] == 0)
2043 break;
2044 return make_unibyte_string (sockun->sun_path, i);
2045 }
2046 #endif
2047 default:
2048 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2049 address = Fcons (make_number (sa->sa_family),
2050 Fmake_vector (make_number (len), Qnil));
2051 p = XVECTOR (XCDR (address));
2052 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2053 break;
2054 }
2055
2056 i = 0;
2057 while (i < len)
2058 p->contents[i++] = make_number (*cp++);
2059
2060 return address;
2061 }
2062
2063
2064 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2065
2066 static int
2067 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2068 {
2069 register struct Lisp_Vector *p;
2070
2071 if (VECTORP (address))
2072 {
2073 p = XVECTOR (address);
2074 if (p->header.size == 5)
2075 {
2076 *familyp = AF_INET;
2077 return sizeof (struct sockaddr_in);
2078 }
2079 #ifdef AF_INET6
2080 else if (p->header.size == 9)
2081 {
2082 *familyp = AF_INET6;
2083 return sizeof (struct sockaddr_in6);
2084 }
2085 #endif
2086 }
2087 #ifdef HAVE_LOCAL_SOCKETS
2088 else if (STRINGP (address))
2089 {
2090 *familyp = AF_LOCAL;
2091 return sizeof (struct sockaddr_un);
2092 }
2093 #endif
2094 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2095 && VECTORP (XCDR (address)))
2096 {
2097 struct sockaddr *sa;
2098 *familyp = XINT (XCAR (address));
2099 p = XVECTOR (XCDR (address));
2100 return p->header.size + sizeof (sa->sa_family);
2101 }
2102 return 0;
2103 }
2104
2105 /* Convert an address object (vector or string) to an internal sockaddr.
2106
2107 The address format has been basically validated by
2108 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2109 it could have come from user data. So if FAMILY is not valid,
2110 we return after zeroing *SA. */
2111
2112 static void
2113 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2114 {
2115 register struct Lisp_Vector *p;
2116 register unsigned char *cp = NULL;
2117 register int i;
2118 EMACS_INT hostport;
2119
2120 memset (sa, 0, len);
2121
2122 if (VECTORP (address))
2123 {
2124 p = XVECTOR (address);
2125 if (family == AF_INET)
2126 {
2127 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2128 len = sizeof (sin->sin_addr) + 1;
2129 hostport = XINT (p->contents[--len]);
2130 sin->sin_port = htons (hostport);
2131 cp = (unsigned char *)&sin->sin_addr;
2132 sa->sa_family = family;
2133 }
2134 #ifdef AF_INET6
2135 else if (family == AF_INET6)
2136 {
2137 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2138 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2139 len = sizeof (sin6->sin6_addr) + 1;
2140 hostport = XINT (p->contents[--len]);
2141 sin6->sin6_port = htons (hostport);
2142 for (i = 0; i < len; i++)
2143 if (INTEGERP (p->contents[i]))
2144 {
2145 int j = XFASTINT (p->contents[i]) & 0xffff;
2146 ip6[i] = ntohs (j);
2147 }
2148 sa->sa_family = family;
2149 return;
2150 }
2151 #endif
2152 else
2153 return;
2154 }
2155 else if (STRINGP (address))
2156 {
2157 #ifdef HAVE_LOCAL_SOCKETS
2158 if (family == AF_LOCAL)
2159 {
2160 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2161 cp = SDATA (address);
2162 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2163 sockun->sun_path[i] = *cp++;
2164 sa->sa_family = family;
2165 }
2166 #endif
2167 return;
2168 }
2169 else
2170 {
2171 p = XVECTOR (XCDR (address));
2172 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2173 }
2174
2175 for (i = 0; i < len; i++)
2176 if (INTEGERP (p->contents[i]))
2177 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2178 }
2179
2180 #ifdef DATAGRAM_SOCKETS
2181 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2182 1, 1, 0,
2183 doc: /* Get the current datagram address associated with PROCESS. */)
2184 (Lisp_Object process)
2185 {
2186 int channel;
2187
2188 CHECK_PROCESS (process);
2189
2190 if (!DATAGRAM_CONN_P (process))
2191 return Qnil;
2192
2193 channel = XPROCESS (process)->infd;
2194 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2195 datagram_address[channel].len);
2196 }
2197
2198 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2199 2, 2, 0,
2200 doc: /* Set the datagram address for PROCESS to ADDRESS.
2201 Returns nil upon error setting address, ADDRESS otherwise. */)
2202 (Lisp_Object process, Lisp_Object address)
2203 {
2204 int channel;
2205 int family, len;
2206
2207 CHECK_PROCESS (process);
2208
2209 if (!DATAGRAM_CONN_P (process))
2210 return Qnil;
2211
2212 channel = XPROCESS (process)->infd;
2213
2214 len = get_lisp_to_sockaddr_size (address, &family);
2215 if (datagram_address[channel].len != len)
2216 return Qnil;
2217 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2218 return address;
2219 }
2220 #endif
2221 \f
2222
2223 static const struct socket_options {
2224 /* The name of this option. Should be lowercase version of option
2225 name without SO_ prefix. */
2226 const char *name;
2227 /* Option level SOL_... */
2228 int optlevel;
2229 /* Option number SO_... */
2230 int optnum;
2231 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2232 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2233 } socket_options[] =
2234 {
2235 #ifdef SO_BINDTODEVICE
2236 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2237 #endif
2238 #ifdef SO_BROADCAST
2239 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2240 #endif
2241 #ifdef SO_DONTROUTE
2242 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2243 #endif
2244 #ifdef SO_KEEPALIVE
2245 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2246 #endif
2247 #ifdef SO_LINGER
2248 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2249 #endif
2250 #ifdef SO_OOBINLINE
2251 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2252 #endif
2253 #ifdef SO_PRIORITY
2254 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2255 #endif
2256 #ifdef SO_REUSEADDR
2257 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2258 #endif
2259 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2260 };
2261
2262 /* Set option OPT to value VAL on socket S.
2263
2264 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2265 Signals an error if setting a known option fails.
2266 */
2267
2268 static int
2269 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2270 {
2271 char *name;
2272 const struct socket_options *sopt;
2273 int ret = 0;
2274
2275 CHECK_SYMBOL (opt);
2276
2277 name = SSDATA (SYMBOL_NAME (opt));
2278 for (sopt = socket_options; sopt->name; sopt++)
2279 if (strcmp (name, sopt->name) == 0)
2280 break;
2281
2282 switch (sopt->opttype)
2283 {
2284 case SOPT_BOOL:
2285 {
2286 int optval;
2287 optval = NILP (val) ? 0 : 1;
2288 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2289 &optval, sizeof (optval));
2290 break;
2291 }
2292
2293 case SOPT_INT:
2294 {
2295 int optval;
2296 if (TYPE_RANGED_INTEGERP (int, val))
2297 optval = XINT (val);
2298 else
2299 error ("Bad option value for %s", name);
2300 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2301 &optval, sizeof (optval));
2302 break;
2303 }
2304
2305 #ifdef SO_BINDTODEVICE
2306 case SOPT_IFNAME:
2307 {
2308 char devname[IFNAMSIZ+1];
2309
2310 /* This is broken, at least in the Linux 2.4 kernel.
2311 To unbind, the arg must be a zero integer, not the empty string.
2312 This should work on all systems. KFS. 2003-09-23. */
2313 memset (devname, 0, sizeof devname);
2314 if (STRINGP (val))
2315 {
2316 char *arg = SSDATA (val);
2317 int len = min (strlen (arg), IFNAMSIZ);
2318 memcpy (devname, arg, len);
2319 }
2320 else if (!NILP (val))
2321 error ("Bad option value for %s", name);
2322 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2323 devname, IFNAMSIZ);
2324 break;
2325 }
2326 #endif
2327
2328 #ifdef SO_LINGER
2329 case SOPT_LINGER:
2330 {
2331 struct linger linger;
2332
2333 linger.l_onoff = 1;
2334 linger.l_linger = 0;
2335 if (TYPE_RANGED_INTEGERP (int, val))
2336 linger.l_linger = XINT (val);
2337 else
2338 linger.l_onoff = NILP (val) ? 0 : 1;
2339 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2340 &linger, sizeof (linger));
2341 break;
2342 }
2343 #endif
2344
2345 default:
2346 return 0;
2347 }
2348
2349 if (ret < 0)
2350 report_file_error ("Cannot set network option",
2351 Fcons (opt, Fcons (val, Qnil)));
2352 return (1 << sopt->optbit);
2353 }
2354
2355
2356 DEFUN ("set-network-process-option",
2357 Fset_network_process_option, Sset_network_process_option,
2358 3, 4, 0,
2359 doc: /* For network process PROCESS set option OPTION to value VALUE.
2360 See `make-network-process' for a list of options and values.
2361 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2362 OPTION is not a supported option, return nil instead; otherwise return t. */)
2363 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2364 {
2365 int s;
2366 struct Lisp_Process *p;
2367
2368 CHECK_PROCESS (process);
2369 p = XPROCESS (process);
2370 if (!NETCONN1_P (p))
2371 error ("Process is not a network process");
2372
2373 s = p->infd;
2374 if (s < 0)
2375 error ("Process is not running");
2376
2377 if (set_socket_option (s, option, value))
2378 {
2379 p->childp = Fplist_put (p->childp, option, value);
2380 return Qt;
2381 }
2382
2383 if (NILP (no_error))
2384 error ("Unknown or unsupported option");
2385
2386 return Qnil;
2387 }
2388
2389 \f
2390 DEFUN ("serial-process-configure",
2391 Fserial_process_configure,
2392 Sserial_process_configure,
2393 0, MANY, 0,
2394 doc: /* Configure speed, bytesize, etc. of a serial process.
2395
2396 Arguments are specified as keyword/argument pairs. Attributes that
2397 are not given are re-initialized from the process's current
2398 configuration (available via the function `process-contact') or set to
2399 reasonable default values. The following arguments are defined:
2400
2401 :process PROCESS
2402 :name NAME
2403 :buffer BUFFER
2404 :port PORT
2405 -- Any of these arguments can be given to identify the process that is
2406 to be configured. If none of these arguments is given, the current
2407 buffer's process is used.
2408
2409 :speed SPEED -- SPEED is the speed of the serial port in bits per
2410 second, also called baud rate. Any value can be given for SPEED, but
2411 most serial ports work only at a few defined values between 1200 and
2412 115200, with 9600 being the most common value. If SPEED is nil, the
2413 serial port is not configured any further, i.e., all other arguments
2414 are ignored. This may be useful for special serial ports such as
2415 Bluetooth-to-serial converters which can only be configured through AT
2416 commands. A value of nil for SPEED can be used only when passed
2417 through `make-serial-process' or `serial-term'.
2418
2419 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2420 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2421
2422 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2423 `odd' (use odd parity), or the symbol `even' (use even parity). If
2424 PARITY is not given, no parity is used.
2425
2426 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2427 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2428 is not given or nil, 1 stopbit is used.
2429
2430 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2431 flowcontrol to be used, which is either nil (don't use flowcontrol),
2432 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2433 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2434 flowcontrol is used.
2435
2436 `serial-process-configure' is called by `make-serial-process' for the
2437 initial configuration of the serial port.
2438
2439 Examples:
2440
2441 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2442
2443 \(serial-process-configure
2444 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2445
2446 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2447
2448 usage: (serial-process-configure &rest ARGS) */)
2449 (ptrdiff_t nargs, Lisp_Object *args)
2450 {
2451 struct Lisp_Process *p;
2452 Lisp_Object contact = Qnil;
2453 Lisp_Object proc = Qnil;
2454 struct gcpro gcpro1;
2455
2456 contact = Flist (nargs, args);
2457 GCPRO1 (contact);
2458
2459 proc = Fplist_get (contact, QCprocess);
2460 if (NILP (proc))
2461 proc = Fplist_get (contact, QCname);
2462 if (NILP (proc))
2463 proc = Fplist_get (contact, QCbuffer);
2464 if (NILP (proc))
2465 proc = Fplist_get (contact, QCport);
2466 proc = get_process (proc);
2467 p = XPROCESS (proc);
2468 if (!EQ (p->type, Qserial))
2469 error ("Not a serial process");
2470
2471 if (NILP (Fplist_get (p->childp, QCspeed)))
2472 {
2473 UNGCPRO;
2474 return Qnil;
2475 }
2476
2477 serial_configure (p, contact);
2478
2479 UNGCPRO;
2480 return Qnil;
2481 }
2482
2483 /* Used by make-serial-process to recover from errors. */
2484 static Lisp_Object
2485 make_serial_process_unwind (Lisp_Object proc)
2486 {
2487 if (!PROCESSP (proc))
2488 abort ();
2489 remove_process (proc);
2490 return Qnil;
2491 }
2492
2493 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2494 0, MANY, 0,
2495 doc: /* Create and return a serial port process.
2496
2497 In Emacs, serial port connections are represented by process objects,
2498 so input and output work as for subprocesses, and `delete-process'
2499 closes a serial port connection. However, a serial process has no
2500 process id, it cannot be signaled, and the status codes are different
2501 from normal processes.
2502
2503 `make-serial-process' creates a process and a buffer, on which you
2504 probably want to use `process-send-string'. Try \\[serial-term] for
2505 an interactive terminal. See below for examples.
2506
2507 Arguments are specified as keyword/argument pairs. The following
2508 arguments are defined:
2509
2510 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2511 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2512 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2513 the backslashes in strings).
2514
2515 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2516 which this function calls.
2517
2518 :name NAME -- NAME is the name of the process. If NAME is not given,
2519 the value of PORT is used.
2520
2521 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2522 with the process. Process output goes at the end of that buffer,
2523 unless you specify an output stream or filter function to handle the
2524 output. If BUFFER is not given, the value of NAME is used.
2525
2526 :coding CODING -- If CODING is a symbol, it specifies the coding
2527 system used for both reading and writing for this process. If CODING
2528 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2529 ENCODING is used for writing.
2530
2531 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2532 the process is running. If BOOL is not given, query before exiting.
2533
2534 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2535 In the stopped state, a serial process does not accept incoming data,
2536 but you can send outgoing data. The stopped state is cleared by
2537 `continue-process' and set by `stop-process'.
2538
2539 :filter FILTER -- Install FILTER as the process filter.
2540
2541 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2542
2543 :plist PLIST -- Install PLIST as the initial plist of the process.
2544
2545 :bytesize
2546 :parity
2547 :stopbits
2548 :flowcontrol
2549 -- This function calls `serial-process-configure' to handle these
2550 arguments.
2551
2552 The original argument list, possibly modified by later configuration,
2553 is available via the function `process-contact'.
2554
2555 Examples:
2556
2557 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2558
2559 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2560
2561 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2562
2563 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2564
2565 usage: (make-serial-process &rest ARGS) */)
2566 (ptrdiff_t nargs, Lisp_Object *args)
2567 {
2568 int fd = -1;
2569 Lisp_Object proc, contact, port;
2570 struct Lisp_Process *p;
2571 struct gcpro gcpro1;
2572 Lisp_Object name, buffer;
2573 Lisp_Object tem, val;
2574 ptrdiff_t specpdl_count = -1;
2575
2576 if (nargs == 0)
2577 return Qnil;
2578
2579 contact = Flist (nargs, args);
2580 GCPRO1 (contact);
2581
2582 port = Fplist_get (contact, QCport);
2583 if (NILP (port))
2584 error ("No port specified");
2585 CHECK_STRING (port);
2586
2587 if (NILP (Fplist_member (contact, QCspeed)))
2588 error (":speed not specified");
2589 if (!NILP (Fplist_get (contact, QCspeed)))
2590 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2591
2592 name = Fplist_get (contact, QCname);
2593 if (NILP (name))
2594 name = port;
2595 CHECK_STRING (name);
2596 proc = make_process (name);
2597 specpdl_count = SPECPDL_INDEX ();
2598 record_unwind_protect (make_serial_process_unwind, proc);
2599 p = XPROCESS (proc);
2600
2601 fd = serial_open (SSDATA (port));
2602 p->infd = fd;
2603 p->outfd = fd;
2604 if (fd > max_process_desc)
2605 max_process_desc = fd;
2606 chan_process[fd] = proc;
2607
2608 buffer = Fplist_get (contact, QCbuffer);
2609 if (NILP (buffer))
2610 buffer = name;
2611 buffer = Fget_buffer_create (buffer);
2612 p->buffer = buffer;
2613
2614 p->childp = contact;
2615 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2616 p->type = Qserial;
2617 p->sentinel = Fplist_get (contact, QCsentinel);
2618 p->filter = Fplist_get (contact, QCfilter);
2619 p->log = Qnil;
2620 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2621 p->kill_without_query = 1;
2622 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2623 p->command = Qt;
2624 p->pty_flag = 0;
2625
2626 if (!EQ (p->command, Qt))
2627 {
2628 FD_SET (fd, &input_wait_mask);
2629 FD_SET (fd, &non_keyboard_wait_mask);
2630 }
2631
2632 if (BUFFERP (buffer))
2633 {
2634 set_marker_both (p->mark, buffer,
2635 BUF_ZV (XBUFFER (buffer)),
2636 BUF_ZV_BYTE (XBUFFER (buffer)));
2637 }
2638
2639 tem = Fplist_member (contact, QCcoding);
2640 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2641 tem = Qnil;
2642
2643 val = Qnil;
2644 if (!NILP (tem))
2645 {
2646 val = XCAR (XCDR (tem));
2647 if (CONSP (val))
2648 val = XCAR (val);
2649 }
2650 else if (!NILP (Vcoding_system_for_read))
2651 val = Vcoding_system_for_read;
2652 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2653 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2654 val = Qnil;
2655 p->decode_coding_system = val;
2656
2657 val = Qnil;
2658 if (!NILP (tem))
2659 {
2660 val = XCAR (XCDR (tem));
2661 if (CONSP (val))
2662 val = XCDR (val);
2663 }
2664 else if (!NILP (Vcoding_system_for_write))
2665 val = Vcoding_system_for_write;
2666 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2667 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2668 val = Qnil;
2669 p->encode_coding_system = val;
2670
2671 setup_process_coding_systems (proc);
2672 p->decoding_buf = empty_unibyte_string;
2673 p->decoding_carryover = 0;
2674 p->encoding_buf = empty_unibyte_string;
2675 p->inherit_coding_system_flag
2676 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2677
2678 Fserial_process_configure (nargs, args);
2679
2680 specpdl_ptr = specpdl + specpdl_count;
2681
2682 UNGCPRO;
2683 return proc;
2684 }
2685
2686 /* Create a network stream/datagram client/server process. Treated
2687 exactly like a normal process when reading and writing. Primary
2688 differences are in status display and process deletion. A network
2689 connection has no PID; you cannot signal it. All you can do is
2690 stop/continue it and deactivate/close it via delete-process */
2691
2692 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2693 0, MANY, 0,
2694 doc: /* Create and return a network server or client process.
2695
2696 In Emacs, network connections are represented by process objects, so
2697 input and output work as for subprocesses and `delete-process' closes
2698 a network connection. However, a network process has no process id,
2699 it cannot be signaled, and the status codes are different from normal
2700 processes.
2701
2702 Arguments are specified as keyword/argument pairs. The following
2703 arguments are defined:
2704
2705 :name NAME -- NAME is name for process. It is modified if necessary
2706 to make it unique.
2707
2708 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2709 with the process. Process output goes at end of that buffer, unless
2710 you specify an output stream or filter function to handle the output.
2711 BUFFER may be also nil, meaning that this process is not associated
2712 with any buffer.
2713
2714 :host HOST -- HOST is name of the host to connect to, or its IP
2715 address. The symbol `local' specifies the local host. If specified
2716 for a server process, it must be a valid name or address for the local
2717 host, and only clients connecting to that address will be accepted.
2718
2719 :service SERVICE -- SERVICE is name of the service desired, or an
2720 integer specifying a port number to connect to. If SERVICE is t,
2721 a random port number is selected for the server. (If Emacs was
2722 compiled with getaddrinfo, a port number can also be specified as a
2723 string, e.g. "80", as well as an integer. This is not portable.)
2724
2725 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2726 stream type connection, `datagram' creates a datagram type connection,
2727 `seqpacket' creates a reliable datagram connection.
2728
2729 :family FAMILY -- FAMILY is the address (and protocol) family for the
2730 service specified by HOST and SERVICE. The default (nil) is to use
2731 whatever address family (IPv4 or IPv6) that is defined for the host
2732 and port number specified by HOST and SERVICE. Other address families
2733 supported are:
2734 local -- for a local (i.e. UNIX) address specified by SERVICE.
2735 ipv4 -- use IPv4 address family only.
2736 ipv6 -- use IPv6 address family only.
2737
2738 :local ADDRESS -- ADDRESS is the local address used for the connection.
2739 This parameter is ignored when opening a client process. When specified
2740 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2741
2742 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2743 connection. This parameter is ignored when opening a stream server
2744 process. For a datagram server process, it specifies the initial
2745 setting of the remote datagram address. When specified for a client
2746 process, the FAMILY, HOST, and SERVICE args are ignored.
2747
2748 The format of ADDRESS depends on the address family:
2749 - An IPv4 address is represented as an vector of integers [A B C D P]
2750 corresponding to numeric IP address A.B.C.D and port number P.
2751 - A local address is represented as a string with the address in the
2752 local address space.
2753 - An "unsupported family" address is represented by a cons (F . AV)
2754 where F is the family number and AV is a vector containing the socket
2755 address data with one element per address data byte. Do not rely on
2756 this format in portable code, as it may depend on implementation
2757 defined constants, data sizes, and data structure alignment.
2758
2759 :coding CODING -- If CODING is a symbol, it specifies the coding
2760 system used for both reading and writing for this process. If CODING
2761 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2762 ENCODING is used for writing.
2763
2764 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2765 return without waiting for the connection to complete; instead, the
2766 sentinel function will be called with second arg matching "open" (if
2767 successful) or "failed" when the connect completes. Default is to use
2768 a blocking connect (i.e. wait) for stream type connections.
2769
2770 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2771 running when Emacs is exited.
2772
2773 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2774 In the stopped state, a server process does not accept new
2775 connections, and a client process does not handle incoming traffic.
2776 The stopped state is cleared by `continue-process' and set by
2777 `stop-process'.
2778
2779 :filter FILTER -- Install FILTER as the process filter.
2780
2781 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2782 process filter are multibyte, otherwise they are unibyte.
2783 If this keyword is not specified, the strings are multibyte if
2784 the default value of `enable-multibyte-characters' is non-nil.
2785
2786 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2787
2788 :log LOG -- Install LOG as the server process log function. This
2789 function is called when the server accepts a network connection from a
2790 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2791 is the server process, CLIENT is the new process for the connection,
2792 and MESSAGE is a string.
2793
2794 :plist PLIST -- Install PLIST as the new process' initial plist.
2795
2796 :server QLEN -- if QLEN is non-nil, create a server process for the
2797 specified FAMILY, SERVICE, and connection type (stream or datagram).
2798 If QLEN is an integer, it is used as the max. length of the server's
2799 pending connection queue (also known as the backlog); the default
2800 queue length is 5. Default is to create a client process.
2801
2802 The following network options can be specified for this connection:
2803
2804 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2805 :dontroute BOOL -- Only send to directly connected hosts.
2806 :keepalive BOOL -- Send keep-alive messages on network stream.
2807 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2808 :oobinline BOOL -- Place out-of-band data in receive data stream.
2809 :priority INT -- Set protocol defined priority for sent packets.
2810 :reuseaddr BOOL -- Allow reusing a recently used local address
2811 (this is allowed by default for a server process).
2812 :bindtodevice NAME -- bind to interface NAME. Using this may require
2813 special privileges on some systems.
2814
2815 Consult the relevant system programmer's manual pages for more
2816 information on using these options.
2817
2818
2819 A server process will listen for and accept connections from clients.
2820 When a client connection is accepted, a new network process is created
2821 for the connection with the following parameters:
2822
2823 - The client's process name is constructed by concatenating the server
2824 process' NAME and a client identification string.
2825 - If the FILTER argument is non-nil, the client process will not get a
2826 separate process buffer; otherwise, the client's process buffer is a newly
2827 created buffer named after the server process' BUFFER name or process
2828 NAME concatenated with the client identification string.
2829 - The connection type and the process filter and sentinel parameters are
2830 inherited from the server process' TYPE, FILTER and SENTINEL.
2831 - The client process' contact info is set according to the client's
2832 addressing information (typically an IP address and a port number).
2833 - The client process' plist is initialized from the server's plist.
2834
2835 Notice that the FILTER and SENTINEL args are never used directly by
2836 the server process. Also, the BUFFER argument is not used directly by
2837 the server process, but via the optional :log function, accepted (and
2838 failed) connections may be logged in the server process' buffer.
2839
2840 The original argument list, modified with the actual connection
2841 information, is available via the `process-contact' function.
2842
2843 usage: (make-network-process &rest ARGS) */)
2844 (ptrdiff_t nargs, Lisp_Object *args)
2845 {
2846 Lisp_Object proc;
2847 Lisp_Object contact;
2848 struct Lisp_Process *p;
2849 #ifdef HAVE_GETADDRINFO
2850 struct addrinfo ai, *res, *lres;
2851 struct addrinfo hints;
2852 const char *portstring;
2853 char portbuf[128];
2854 #else /* HAVE_GETADDRINFO */
2855 struct _emacs_addrinfo
2856 {
2857 int ai_family;
2858 int ai_socktype;
2859 int ai_protocol;
2860 int ai_addrlen;
2861 struct sockaddr *ai_addr;
2862 struct _emacs_addrinfo *ai_next;
2863 } ai, *res, *lres;
2864 #endif /* HAVE_GETADDRINFO */
2865 struct sockaddr_in address_in;
2866 #ifdef HAVE_LOCAL_SOCKETS
2867 struct sockaddr_un address_un;
2868 #endif
2869 int port;
2870 int ret = 0;
2871 int xerrno = 0;
2872 int s = -1, outch, inch;
2873 struct gcpro gcpro1;
2874 ptrdiff_t count = SPECPDL_INDEX ();
2875 ptrdiff_t count1;
2876 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2877 Lisp_Object tem;
2878 Lisp_Object name, buffer, host, service, address;
2879 Lisp_Object filter, sentinel;
2880 int is_non_blocking_client = 0;
2881 int is_server = 0, backlog = 5;
2882 int socktype;
2883 int family = -1;
2884
2885 if (nargs == 0)
2886 return Qnil;
2887
2888 /* Save arguments for process-contact and clone-process. */
2889 contact = Flist (nargs, args);
2890 GCPRO1 (contact);
2891
2892 #ifdef WINDOWSNT
2893 /* Ensure socket support is loaded if available. */
2894 init_winsock (TRUE);
2895 #endif
2896
2897 /* :type TYPE (nil: stream, datagram */
2898 tem = Fplist_get (contact, QCtype);
2899 if (NILP (tem))
2900 socktype = SOCK_STREAM;
2901 #ifdef DATAGRAM_SOCKETS
2902 else if (EQ (tem, Qdatagram))
2903 socktype = SOCK_DGRAM;
2904 #endif
2905 #ifdef HAVE_SEQPACKET
2906 else if (EQ (tem, Qseqpacket))
2907 socktype = SOCK_SEQPACKET;
2908 #endif
2909 else
2910 error ("Unsupported connection type");
2911
2912 /* :server BOOL */
2913 tem = Fplist_get (contact, QCserver);
2914 if (!NILP (tem))
2915 {
2916 /* Don't support network sockets when non-blocking mode is
2917 not available, since a blocked Emacs is not useful. */
2918 #if !defined (O_NONBLOCK) && !defined (O_NDELAY)
2919 error ("Network servers not supported");
2920 #else
2921 is_server = 1;
2922 if (TYPE_RANGED_INTEGERP (int, tem))
2923 backlog = XINT (tem);
2924 #endif
2925 }
2926
2927 /* Make QCaddress an alias for :local (server) or :remote (client). */
2928 QCaddress = is_server ? QClocal : QCremote;
2929
2930 /* :nowait BOOL */
2931 if (!is_server && socktype != SOCK_DGRAM
2932 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2933 {
2934 #ifndef NON_BLOCKING_CONNECT
2935 error ("Non-blocking connect not supported");
2936 #else
2937 is_non_blocking_client = 1;
2938 #endif
2939 }
2940
2941 name = Fplist_get (contact, QCname);
2942 buffer = Fplist_get (contact, QCbuffer);
2943 filter = Fplist_get (contact, QCfilter);
2944 sentinel = Fplist_get (contact, QCsentinel);
2945
2946 CHECK_STRING (name);
2947
2948 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2949 ai.ai_socktype = socktype;
2950 ai.ai_protocol = 0;
2951 ai.ai_next = NULL;
2952 res = &ai;
2953
2954 /* :local ADDRESS or :remote ADDRESS */
2955 address = Fplist_get (contact, QCaddress);
2956 if (!NILP (address))
2957 {
2958 host = service = Qnil;
2959
2960 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2961 error ("Malformed :address");
2962 ai.ai_family = family;
2963 ai.ai_addr = alloca (ai.ai_addrlen);
2964 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2965 goto open_socket;
2966 }
2967
2968 /* :family FAMILY -- nil (for Inet), local, or integer. */
2969 tem = Fplist_get (contact, QCfamily);
2970 if (NILP (tem))
2971 {
2972 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2973 family = AF_UNSPEC;
2974 #else
2975 family = AF_INET;
2976 #endif
2977 }
2978 #ifdef HAVE_LOCAL_SOCKETS
2979 else if (EQ (tem, Qlocal))
2980 family = AF_LOCAL;
2981 #endif
2982 #ifdef AF_INET6
2983 else if (EQ (tem, Qipv6))
2984 family = AF_INET6;
2985 #endif
2986 else if (EQ (tem, Qipv4))
2987 family = AF_INET;
2988 else if (TYPE_RANGED_INTEGERP (int, tem))
2989 family = XINT (tem);
2990 else
2991 error ("Unknown address family");
2992
2993 ai.ai_family = family;
2994
2995 /* :service SERVICE -- string, integer (port number), or t (random port). */
2996 service = Fplist_get (contact, QCservice);
2997
2998 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2999 host = Fplist_get (contact, QChost);
3000 if (!NILP (host))
3001 {
3002 if (EQ (host, Qlocal))
3003 /* Depending on setup, "localhost" may map to different IPv4 and/or
3004 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
3005 host = build_string ("127.0.0.1");
3006 CHECK_STRING (host);
3007 }
3008
3009 #ifdef HAVE_LOCAL_SOCKETS
3010 if (family == AF_LOCAL)
3011 {
3012 if (!NILP (host))
3013 {
3014 message (":family local ignores the :host \"%s\" property",
3015 SDATA (host));
3016 contact = Fplist_put (contact, QChost, Qnil);
3017 host = Qnil;
3018 }
3019 CHECK_STRING (service);
3020 memset (&address_un, 0, sizeof address_un);
3021 address_un.sun_family = AF_LOCAL;
3022 strncpy (address_un.sun_path, SSDATA (service), sizeof address_un.sun_path);
3023 ai.ai_addr = (struct sockaddr *) &address_un;
3024 ai.ai_addrlen = sizeof address_un;
3025 goto open_socket;
3026 }
3027 #endif
3028
3029 /* Slow down polling to every ten seconds.
3030 Some kernels have a bug which causes retrying connect to fail
3031 after a connect. Polling can interfere with gethostbyname too. */
3032 #ifdef POLL_FOR_INPUT
3033 if (socktype != SOCK_DGRAM)
3034 {
3035 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3036 bind_polling_period (10);
3037 }
3038 #endif
3039
3040 #ifdef HAVE_GETADDRINFO
3041 /* If we have a host, use getaddrinfo to resolve both host and service.
3042 Otherwise, use getservbyname to lookup the service. */
3043 if (!NILP (host))
3044 {
3045
3046 /* SERVICE can either be a string or int.
3047 Convert to a C string for later use by getaddrinfo. */
3048 if (EQ (service, Qt))
3049 portstring = "0";
3050 else if (INTEGERP (service))
3051 {
3052 sprintf (portbuf, "%"pI"d", XINT (service));
3053 portstring = portbuf;
3054 }
3055 else
3056 {
3057 CHECK_STRING (service);
3058 portstring = SSDATA (service);
3059 }
3060
3061 immediate_quit = 1;
3062 QUIT;
3063 memset (&hints, 0, sizeof (hints));
3064 hints.ai_flags = 0;
3065 hints.ai_family = family;
3066 hints.ai_socktype = socktype;
3067 hints.ai_protocol = 0;
3068
3069 #ifdef HAVE_RES_INIT
3070 res_init ();
3071 #endif
3072
3073 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3074 if (ret)
3075 #ifdef HAVE_GAI_STRERROR
3076 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3077 #else
3078 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3079 #endif
3080 immediate_quit = 0;
3081
3082 goto open_socket;
3083 }
3084 #endif /* HAVE_GETADDRINFO */
3085
3086 /* We end up here if getaddrinfo is not defined, or in case no hostname
3087 has been specified (e.g. for a local server process). */
3088
3089 if (EQ (service, Qt))
3090 port = 0;
3091 else if (INTEGERP (service))
3092 port = htons ((unsigned short) XINT (service));
3093 else
3094 {
3095 struct servent *svc_info;
3096 CHECK_STRING (service);
3097 svc_info = getservbyname (SSDATA (service),
3098 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3099 if (svc_info == 0)
3100 error ("Unknown service: %s", SDATA (service));
3101 port = svc_info->s_port;
3102 }
3103
3104 memset (&address_in, 0, sizeof address_in);
3105 address_in.sin_family = family;
3106 address_in.sin_addr.s_addr = INADDR_ANY;
3107 address_in.sin_port = port;
3108
3109 #ifndef HAVE_GETADDRINFO
3110 if (!NILP (host))
3111 {
3112 struct hostent *host_info_ptr;
3113
3114 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3115 as it may `hang' Emacs for a very long time. */
3116 immediate_quit = 1;
3117 QUIT;
3118
3119 #ifdef HAVE_RES_INIT
3120 res_init ();
3121 #endif
3122
3123 host_info_ptr = gethostbyname (SDATA (host));
3124 immediate_quit = 0;
3125
3126 if (host_info_ptr)
3127 {
3128 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3129 host_info_ptr->h_length);
3130 family = host_info_ptr->h_addrtype;
3131 address_in.sin_family = family;
3132 }
3133 else
3134 /* Attempt to interpret host as numeric inet address */
3135 {
3136 unsigned long numeric_addr;
3137 numeric_addr = inet_addr (SSDATA (host));
3138 if (numeric_addr == -1)
3139 error ("Unknown host \"%s\"", SDATA (host));
3140
3141 memcpy (&address_in.sin_addr, &numeric_addr,
3142 sizeof (address_in.sin_addr));
3143 }
3144
3145 }
3146 #endif /* not HAVE_GETADDRINFO */
3147
3148 ai.ai_family = family;
3149 ai.ai_addr = (struct sockaddr *) &address_in;
3150 ai.ai_addrlen = sizeof address_in;
3151
3152 open_socket:
3153
3154 /* Do this in case we never enter the for-loop below. */
3155 count1 = SPECPDL_INDEX ();
3156 s = -1;
3157
3158 for (lres = res; lres; lres = lres->ai_next)
3159 {
3160 ptrdiff_t optn;
3161 int optbits;
3162
3163 #ifdef WINDOWSNT
3164 retry_connect:
3165 #endif
3166
3167 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3168 if (s < 0)
3169 {
3170 xerrno = errno;
3171 continue;
3172 }
3173
3174 #ifdef DATAGRAM_SOCKETS
3175 if (!is_server && socktype == SOCK_DGRAM)
3176 break;
3177 #endif /* DATAGRAM_SOCKETS */
3178
3179 #ifdef NON_BLOCKING_CONNECT
3180 if (is_non_blocking_client)
3181 {
3182 #ifdef O_NONBLOCK
3183 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3184 #else
3185 ret = fcntl (s, F_SETFL, O_NDELAY);
3186 #endif
3187 if (ret < 0)
3188 {
3189 xerrno = errno;
3190 emacs_close (s);
3191 s = -1;
3192 continue;
3193 }
3194 }
3195 #endif
3196
3197 /* Make us close S if quit. */
3198 record_unwind_protect (close_file_unwind, make_number (s));
3199
3200 /* Parse network options in the arg list.
3201 We simply ignore anything which isn't a known option (including other keywords).
3202 An error is signaled if setting a known option fails. */
3203 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3204 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3205
3206 if (is_server)
3207 {
3208 /* Configure as a server socket. */
3209
3210 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3211 explicit :reuseaddr key to override this. */
3212 #ifdef HAVE_LOCAL_SOCKETS
3213 if (family != AF_LOCAL)
3214 #endif
3215 if (!(optbits & (1 << OPIX_REUSEADDR)))
3216 {
3217 int optval = 1;
3218 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3219 report_file_error ("Cannot set reuse option on server socket", Qnil);
3220 }
3221
3222 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3223 report_file_error ("Cannot bind server socket", Qnil);
3224
3225 #ifdef HAVE_GETSOCKNAME
3226 if (EQ (service, Qt))
3227 {
3228 struct sockaddr_in sa1;
3229 socklen_t len1 = sizeof (sa1);
3230 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3231 {
3232 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3233 service = make_number (ntohs (sa1.sin_port));
3234 contact = Fplist_put (contact, QCservice, service);
3235 }
3236 }
3237 #endif
3238
3239 if (socktype != SOCK_DGRAM && listen (s, backlog))
3240 report_file_error ("Cannot listen on server socket", Qnil);
3241
3242 break;
3243 }
3244
3245 immediate_quit = 1;
3246 QUIT;
3247
3248 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3249 xerrno = errno;
3250
3251 if (ret == 0 || xerrno == EISCONN)
3252 {
3253 /* The unwind-protect will be discarded afterwards.
3254 Likewise for immediate_quit. */
3255 break;
3256 }
3257
3258 #ifdef NON_BLOCKING_CONNECT
3259 #ifdef EINPROGRESS
3260 if (is_non_blocking_client && xerrno == EINPROGRESS)
3261 break;
3262 #else
3263 #ifdef EWOULDBLOCK
3264 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3265 break;
3266 #endif
3267 #endif
3268 #endif
3269
3270 #ifndef WINDOWSNT
3271 if (xerrno == EINTR)
3272 {
3273 /* Unlike most other syscalls connect() cannot be called
3274 again. (That would return EALREADY.) The proper way to
3275 wait for completion is pselect(). */
3276 int sc;
3277 socklen_t len;
3278 SELECT_TYPE fdset;
3279 retry_select:
3280 FD_ZERO (&fdset);
3281 FD_SET (s, &fdset);
3282 QUIT;
3283 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3284 if (sc == -1)
3285 {
3286 if (errno == EINTR)
3287 goto retry_select;
3288 else
3289 report_file_error ("select failed", Qnil);
3290 }
3291 eassert (sc > 0);
3292
3293 len = sizeof xerrno;
3294 eassert (FD_ISSET (s, &fdset));
3295 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3296 report_file_error ("getsockopt failed", Qnil);
3297 if (xerrno)
3298 errno = xerrno, report_file_error ("error during connect", Qnil);
3299 else
3300 break;
3301 }
3302 #endif /* !WINDOWSNT */
3303
3304 immediate_quit = 0;
3305
3306 /* Discard the unwind protect closing S. */
3307 specpdl_ptr = specpdl + count1;
3308 emacs_close (s);
3309 s = -1;
3310
3311 #ifdef WINDOWSNT
3312 if (xerrno == EINTR)
3313 goto retry_connect;
3314 #endif
3315 }
3316
3317 if (s >= 0)
3318 {
3319 #ifdef DATAGRAM_SOCKETS
3320 if (socktype == SOCK_DGRAM)
3321 {
3322 if (datagram_address[s].sa)
3323 abort ();
3324 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3325 datagram_address[s].len = lres->ai_addrlen;
3326 if (is_server)
3327 {
3328 Lisp_Object remote;
3329 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3330 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3331 {
3332 int rfamily, rlen;
3333 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3334 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3335 conv_lisp_to_sockaddr (rfamily, remote,
3336 datagram_address[s].sa, rlen);
3337 }
3338 }
3339 else
3340 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3341 }
3342 #endif
3343 contact = Fplist_put (contact, QCaddress,
3344 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3345 #ifdef HAVE_GETSOCKNAME
3346 if (!is_server)
3347 {
3348 struct sockaddr_in sa1;
3349 socklen_t len1 = sizeof (sa1);
3350 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3351 contact = Fplist_put (contact, QClocal,
3352 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3353 }
3354 #endif
3355 }
3356
3357 immediate_quit = 0;
3358
3359 #ifdef HAVE_GETADDRINFO
3360 if (res != &ai)
3361 {
3362 BLOCK_INPUT;
3363 freeaddrinfo (res);
3364 UNBLOCK_INPUT;
3365 }
3366 #endif
3367
3368 /* Discard the unwind protect for closing S, if any. */
3369 specpdl_ptr = specpdl + count1;
3370
3371 /* Unwind bind_polling_period and request_sigio. */
3372 unbind_to (count, Qnil);
3373
3374 if (s < 0)
3375 {
3376 /* If non-blocking got this far - and failed - assume non-blocking is
3377 not supported after all. This is probably a wrong assumption, but
3378 the normal blocking calls to open-network-stream handles this error
3379 better. */
3380 if (is_non_blocking_client)
3381 return Qnil;
3382
3383 errno = xerrno;
3384 if (is_server)
3385 report_file_error ("make server process failed", contact);
3386 else
3387 report_file_error ("make client process failed", contact);
3388 }
3389
3390 inch = s;
3391 outch = s;
3392
3393 if (!NILP (buffer))
3394 buffer = Fget_buffer_create (buffer);
3395 proc = make_process (name);
3396
3397 chan_process[inch] = proc;
3398
3399 #ifdef O_NONBLOCK
3400 fcntl (inch, F_SETFL, O_NONBLOCK);
3401 #else
3402 #ifdef O_NDELAY
3403 fcntl (inch, F_SETFL, O_NDELAY);
3404 #endif
3405 #endif
3406
3407 p = XPROCESS (proc);
3408
3409 p->childp = contact;
3410 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3411 p->type = Qnetwork;
3412
3413 p->buffer = buffer;
3414 p->sentinel = sentinel;
3415 p->filter = filter;
3416 p->log = Fplist_get (contact, QClog);
3417 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3418 p->kill_without_query = 1;
3419 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3420 p->command = Qt;
3421 p->pid = 0;
3422 p->infd = inch;
3423 p->outfd = outch;
3424 if (is_server && socktype != SOCK_DGRAM)
3425 p->status = Qlisten;
3426
3427 /* Make the process marker point into the process buffer (if any). */
3428 if (BUFFERP (buffer))
3429 set_marker_both (p->mark, buffer,
3430 BUF_ZV (XBUFFER (buffer)),
3431 BUF_ZV_BYTE (XBUFFER (buffer)));
3432
3433 #ifdef NON_BLOCKING_CONNECT
3434 if (is_non_blocking_client)
3435 {
3436 /* We may get here if connect did succeed immediately. However,
3437 in that case, we still need to signal this like a non-blocking
3438 connection. */
3439 p->status = Qconnect;
3440 if (!FD_ISSET (inch, &connect_wait_mask))
3441 {
3442 FD_SET (inch, &connect_wait_mask);
3443 FD_SET (inch, &write_mask);
3444 num_pending_connects++;
3445 }
3446 }
3447 else
3448 #endif
3449 /* A server may have a client filter setting of Qt, but it must
3450 still listen for incoming connects unless it is stopped. */
3451 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3452 || (EQ (p->status, Qlisten) && NILP (p->command)))
3453 {
3454 FD_SET (inch, &input_wait_mask);
3455 FD_SET (inch, &non_keyboard_wait_mask);
3456 }
3457
3458 if (inch > max_process_desc)
3459 max_process_desc = inch;
3460
3461 tem = Fplist_member (contact, QCcoding);
3462 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3463 tem = Qnil; /* No error message (too late!). */
3464
3465 {
3466 /* Setup coding systems for communicating with the network stream. */
3467 struct gcpro gcpro1;
3468 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3469 Lisp_Object coding_systems = Qt;
3470 Lisp_Object fargs[5], val;
3471
3472 if (!NILP (tem))
3473 {
3474 val = XCAR (XCDR (tem));
3475 if (CONSP (val))
3476 val = XCAR (val);
3477 }
3478 else if (!NILP (Vcoding_system_for_read))
3479 val = Vcoding_system_for_read;
3480 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3481 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3482 /* We dare not decode end-of-line format by setting VAL to
3483 Qraw_text, because the existing Emacs Lisp libraries
3484 assume that they receive bare code including a sequence of
3485 CR LF. */
3486 val = Qnil;
3487 else
3488 {
3489 if (NILP (host) || NILP (service))
3490 coding_systems = Qnil;
3491 else
3492 {
3493 fargs[0] = Qopen_network_stream, fargs[1] = name,
3494 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3495 GCPRO1 (proc);
3496 coding_systems = Ffind_operation_coding_system (5, fargs);
3497 UNGCPRO;
3498 }
3499 if (CONSP (coding_systems))
3500 val = XCAR (coding_systems);
3501 else if (CONSP (Vdefault_process_coding_system))
3502 val = XCAR (Vdefault_process_coding_system);
3503 else
3504 val = Qnil;
3505 }
3506 p->decode_coding_system = val;
3507
3508 if (!NILP (tem))
3509 {
3510 val = XCAR (XCDR (tem));
3511 if (CONSP (val))
3512 val = XCDR (val);
3513 }
3514 else if (!NILP (Vcoding_system_for_write))
3515 val = Vcoding_system_for_write;
3516 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3517 val = Qnil;
3518 else
3519 {
3520 if (EQ (coding_systems, Qt))
3521 {
3522 if (NILP (host) || NILP (service))
3523 coding_systems = Qnil;
3524 else
3525 {
3526 fargs[0] = Qopen_network_stream, fargs[1] = name,
3527 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3528 GCPRO1 (proc);
3529 coding_systems = Ffind_operation_coding_system (5, fargs);
3530 UNGCPRO;
3531 }
3532 }
3533 if (CONSP (coding_systems))
3534 val = XCDR (coding_systems);
3535 else if (CONSP (Vdefault_process_coding_system))
3536 val = XCDR (Vdefault_process_coding_system);
3537 else
3538 val = Qnil;
3539 }
3540 p->encode_coding_system = val;
3541 }
3542 setup_process_coding_systems (proc);
3543
3544 p->decoding_buf = empty_unibyte_string;
3545 p->decoding_carryover = 0;
3546 p->encoding_buf = empty_unibyte_string;
3547
3548 p->inherit_coding_system_flag
3549 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3550
3551 UNGCPRO;
3552 return proc;
3553 }
3554
3555 \f
3556 #if defined (HAVE_NET_IF_H)
3557
3558 #ifdef SIOCGIFCONF
3559 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3560 doc: /* Return an alist of all network interfaces and their network address.
3561 Each element is a cons, the car of which is a string containing the
3562 interface name, and the cdr is the network address in internal
3563 format; see the description of ADDRESS in `make-network-process'. */)
3564 (void)
3565 {
3566 struct ifconf ifconf;
3567 struct ifreq *ifreq;
3568 void *buf = NULL;
3569 ptrdiff_t buf_size = 512;
3570 int s, i;
3571 Lisp_Object res;
3572
3573 s = socket (AF_INET, SOCK_STREAM, 0);
3574 if (s < 0)
3575 return Qnil;
3576
3577 do
3578 {
3579 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3580 ifconf.ifc_buf = buf;
3581 ifconf.ifc_len = buf_size;
3582 if (ioctl (s, SIOCGIFCONF, &ifconf))
3583 {
3584 close (s);
3585 xfree (buf);
3586 return Qnil;
3587 }
3588 }
3589 while (ifconf.ifc_len == buf_size);
3590
3591 close (s);
3592
3593 res = Qnil;
3594 ifreq = ifconf.ifc_req;
3595 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3596 {
3597 struct ifreq *ifq = ifreq;
3598 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3599 #define SIZEOF_IFREQ(sif) \
3600 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3601 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3602
3603 int len = SIZEOF_IFREQ (ifq);
3604 #else
3605 int len = sizeof (*ifreq);
3606 #endif
3607 char namebuf[sizeof (ifq->ifr_name) + 1];
3608 i += len;
3609 ifreq = (struct ifreq *) ((char *) ifreq + len);
3610
3611 if (ifq->ifr_addr.sa_family != AF_INET)
3612 continue;
3613
3614 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3615 namebuf[sizeof (ifq->ifr_name)] = 0;
3616 res = Fcons (Fcons (build_string (namebuf),
3617 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3618 sizeof (struct sockaddr))),
3619 res);
3620 }
3621
3622 xfree (buf);
3623 return res;
3624 }
3625 #endif /* SIOCGIFCONF */
3626
3627 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3628
3629 struct ifflag_def {
3630 int flag_bit;
3631 const char *flag_sym;
3632 };
3633
3634 static const struct ifflag_def ifflag_table[] = {
3635 #ifdef IFF_UP
3636 { IFF_UP, "up" },
3637 #endif
3638 #ifdef IFF_BROADCAST
3639 { IFF_BROADCAST, "broadcast" },
3640 #endif
3641 #ifdef IFF_DEBUG
3642 { IFF_DEBUG, "debug" },
3643 #endif
3644 #ifdef IFF_LOOPBACK
3645 { IFF_LOOPBACK, "loopback" },
3646 #endif
3647 #ifdef IFF_POINTOPOINT
3648 { IFF_POINTOPOINT, "pointopoint" },
3649 #endif
3650 #ifdef IFF_RUNNING
3651 { IFF_RUNNING, "running" },
3652 #endif
3653 #ifdef IFF_NOARP
3654 { IFF_NOARP, "noarp" },
3655 #endif
3656 #ifdef IFF_PROMISC
3657 { IFF_PROMISC, "promisc" },
3658 #endif
3659 #ifdef IFF_NOTRAILERS
3660 #ifdef NS_IMPL_COCOA
3661 /* Really means smart, notrailers is obsolete */
3662 { IFF_NOTRAILERS, "smart" },
3663 #else
3664 { IFF_NOTRAILERS, "notrailers" },
3665 #endif
3666 #endif
3667 #ifdef IFF_ALLMULTI
3668 { IFF_ALLMULTI, "allmulti" },
3669 #endif
3670 #ifdef IFF_MASTER
3671 { IFF_MASTER, "master" },
3672 #endif
3673 #ifdef IFF_SLAVE
3674 { IFF_SLAVE, "slave" },
3675 #endif
3676 #ifdef IFF_MULTICAST
3677 { IFF_MULTICAST, "multicast" },
3678 #endif
3679 #ifdef IFF_PORTSEL
3680 { IFF_PORTSEL, "portsel" },
3681 #endif
3682 #ifdef IFF_AUTOMEDIA
3683 { IFF_AUTOMEDIA, "automedia" },
3684 #endif
3685 #ifdef IFF_DYNAMIC
3686 { IFF_DYNAMIC, "dynamic" },
3687 #endif
3688 #ifdef IFF_OACTIVE
3689 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3690 #endif
3691 #ifdef IFF_SIMPLEX
3692 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3693 #endif
3694 #ifdef IFF_LINK0
3695 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3696 #endif
3697 #ifdef IFF_LINK1
3698 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3699 #endif
3700 #ifdef IFF_LINK2
3701 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3702 #endif
3703 { 0, 0 }
3704 };
3705
3706 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3707 doc: /* Return information about network interface named IFNAME.
3708 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3709 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3710 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3711 FLAGS is the current flags of the interface. */)
3712 (Lisp_Object ifname)
3713 {
3714 struct ifreq rq;
3715 Lisp_Object res = Qnil;
3716 Lisp_Object elt;
3717 int s;
3718 int any = 0;
3719 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3720 && defined HAVE_GETIFADDRS && defined LLADDR)
3721 struct ifaddrs *ifap;
3722 #endif
3723
3724 CHECK_STRING (ifname);
3725
3726 memset (rq.ifr_name, 0, sizeof rq.ifr_name);
3727 strncpy (rq.ifr_name, SSDATA (ifname), sizeof (rq.ifr_name));
3728
3729 s = socket (AF_INET, SOCK_STREAM, 0);
3730 if (s < 0)
3731 return Qnil;
3732
3733 elt = Qnil;
3734 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3735 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3736 {
3737 int flags = rq.ifr_flags;
3738 const struct ifflag_def *fp;
3739 int fnum;
3740
3741 /* If flags is smaller than int (i.e. short) it may have the high bit set
3742 due to IFF_MULTICAST. In that case, sign extending it into
3743 an int is wrong. */
3744 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3745 flags = (unsigned short) rq.ifr_flags;
3746
3747 any = 1;
3748 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3749 {
3750 if (flags & fp->flag_bit)
3751 {
3752 elt = Fcons (intern (fp->flag_sym), elt);
3753 flags -= fp->flag_bit;
3754 }
3755 }
3756 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3757 {
3758 if (flags & 1)
3759 {
3760 elt = Fcons (make_number (fnum), elt);
3761 }
3762 }
3763 }
3764 #endif
3765 res = Fcons (elt, res);
3766
3767 elt = Qnil;
3768 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3769 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3770 {
3771 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3772 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3773 int n;
3774
3775 any = 1;
3776 for (n = 0; n < 6; n++)
3777 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3778 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3779 }
3780 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3781 if (getifaddrs (&ifap) != -1)
3782 {
3783 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3784 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3785 struct ifaddrs *it;
3786
3787 for (it = ifap; it != NULL; it = it->ifa_next)
3788 {
3789 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3790 unsigned char linkaddr[6];
3791 int n;
3792
3793 if (it->ifa_addr->sa_family != AF_LINK
3794 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3795 || sdl->sdl_alen != 6)
3796 continue;
3797
3798 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3799 for (n = 0; n < 6; n++)
3800 p->contents[n] = make_number (linkaddr[n]);
3801
3802 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3803 break;
3804 }
3805 }
3806 #ifdef HAVE_FREEIFADDRS
3807 freeifaddrs (ifap);
3808 #endif
3809
3810 #endif /* HAVE_GETIFADDRS && LLADDR */
3811
3812 res = Fcons (elt, res);
3813
3814 elt = Qnil;
3815 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3816 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3817 {
3818 any = 1;
3819 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3820 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3821 #else
3822 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3823 #endif
3824 }
3825 #endif
3826 res = Fcons (elt, res);
3827
3828 elt = Qnil;
3829 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3830 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3831 {
3832 any = 1;
3833 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3834 }
3835 #endif
3836 res = Fcons (elt, res);
3837
3838 elt = Qnil;
3839 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3840 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3841 {
3842 any = 1;
3843 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3844 }
3845 #endif
3846 res = Fcons (elt, res);
3847
3848 close (s);
3849
3850 return any ? res : Qnil;
3851 }
3852 #endif
3853 #endif /* defined (HAVE_NET_IF_H) */
3854
3855 /* Turn off input and output for process PROC. */
3856
3857 static void
3858 deactivate_process (Lisp_Object proc)
3859 {
3860 register int inchannel, outchannel;
3861 register struct Lisp_Process *p = XPROCESS (proc);
3862
3863 #ifdef HAVE_GNUTLS
3864 /* Delete GnuTLS structures in PROC, if any. */
3865 emacs_gnutls_deinit (proc);
3866 #endif /* HAVE_GNUTLS */
3867
3868 inchannel = p->infd;
3869 outchannel = p->outfd;
3870
3871 #ifdef ADAPTIVE_READ_BUFFERING
3872 if (p->read_output_delay > 0)
3873 {
3874 if (--process_output_delay_count < 0)
3875 process_output_delay_count = 0;
3876 p->read_output_delay = 0;
3877 p->read_output_skip = 0;
3878 }
3879 #endif
3880
3881 if (inchannel >= 0)
3882 {
3883 /* Beware SIGCHLD hereabouts. */
3884 flush_pending_output (inchannel);
3885 emacs_close (inchannel);
3886 if (outchannel >= 0 && outchannel != inchannel)
3887 emacs_close (outchannel);
3888
3889 p->infd = -1;
3890 p->outfd = -1;
3891 #ifdef DATAGRAM_SOCKETS
3892 if (DATAGRAM_CHAN_P (inchannel))
3893 {
3894 xfree (datagram_address[inchannel].sa);
3895 datagram_address[inchannel].sa = 0;
3896 datagram_address[inchannel].len = 0;
3897 }
3898 #endif
3899 chan_process[inchannel] = Qnil;
3900 FD_CLR (inchannel, &input_wait_mask);
3901 FD_CLR (inchannel, &non_keyboard_wait_mask);
3902 #ifdef NON_BLOCKING_CONNECT
3903 if (FD_ISSET (inchannel, &connect_wait_mask))
3904 {
3905 FD_CLR (inchannel, &connect_wait_mask);
3906 FD_CLR (inchannel, &write_mask);
3907 if (--num_pending_connects < 0)
3908 abort ();
3909 }
3910 #endif
3911 if (inchannel == max_process_desc)
3912 {
3913 int i;
3914 /* We just closed the highest-numbered process input descriptor,
3915 so recompute the highest-numbered one now. */
3916 max_process_desc = 0;
3917 for (i = 0; i < MAXDESC; i++)
3918 if (!NILP (chan_process[i]))
3919 max_process_desc = i;
3920 }
3921 }
3922 }
3923
3924 \f
3925 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3926 0, 4, 0,
3927 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3928 It is read into the process' buffers or given to their filter functions.
3929 Non-nil arg PROCESS means do not return until some output has been received
3930 from PROCESS.
3931
3932 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
3933 and milliseconds to wait; return after that much time whether or not
3934 there is any subprocess output. If SECONDS is a floating point number,
3935 it specifies a fractional number of seconds to wait.
3936 The MILLISEC argument is obsolete and should be avoided.
3937
3938 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3939 from PROCESS, suspending reading output from other processes.
3940 If JUST-THIS-ONE is an integer, don't run any timers either.
3941 Return non-nil if we received any output before the timeout expired. */)
3942 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
3943 {
3944 intmax_t secs;
3945 int nsecs;
3946
3947 if (! NILP (process))
3948 CHECK_PROCESS (process);
3949 else
3950 just_this_one = Qnil;
3951
3952 if (!NILP (millisec))
3953 { /* Obsolete calling convention using integers rather than floats. */
3954 CHECK_NUMBER (millisec);
3955 if (NILP (seconds))
3956 seconds = make_float (XINT (millisec) / 1000.0);
3957 else
3958 {
3959 CHECK_NUMBER (seconds);
3960 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
3961 }
3962 }
3963
3964 secs = 0;
3965 nsecs = -1;
3966
3967 if (!NILP (seconds))
3968 {
3969 if (INTEGERP (seconds))
3970 {
3971 if (0 < XINT (seconds))
3972 {
3973 secs = XINT (seconds);
3974 nsecs = 0;
3975 }
3976 }
3977 else if (FLOATP (seconds))
3978 {
3979 if (0 < XFLOAT_DATA (seconds))
3980 {
3981 EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (XFLOAT_DATA (seconds));
3982 secs = min (EMACS_SECS (t), WAIT_READING_MAX);
3983 nsecs = EMACS_NSECS (t);
3984 }
3985 }
3986 else
3987 wrong_type_argument (Qnumberp, seconds);
3988 }
3989 else if (! NILP (process))
3990 nsecs = 0;
3991
3992 return
3993 (wait_reading_process_output (secs, nsecs, 0, 0,
3994 Qnil,
3995 !NILP (process) ? XPROCESS (process) : NULL,
3996 NILP (just_this_one) ? 0 :
3997 !INTEGERP (just_this_one) ? 1 : -1)
3998 ? Qt : Qnil);
3999 }
4000
4001 /* Accept a connection for server process SERVER on CHANNEL. */
4002
4003 static int connect_counter = 0;
4004
4005 static void
4006 server_accept_connection (Lisp_Object server, int channel)
4007 {
4008 Lisp_Object proc, caller, name, buffer;
4009 Lisp_Object contact, host, service;
4010 struct Lisp_Process *ps= XPROCESS (server);
4011 struct Lisp_Process *p;
4012 int s;
4013 union u_sockaddr {
4014 struct sockaddr sa;
4015 struct sockaddr_in in;
4016 #ifdef AF_INET6
4017 struct sockaddr_in6 in6;
4018 #endif
4019 #ifdef HAVE_LOCAL_SOCKETS
4020 struct sockaddr_un un;
4021 #endif
4022 } saddr;
4023 socklen_t len = sizeof saddr;
4024
4025 s = accept (channel, &saddr.sa, &len);
4026
4027 if (s < 0)
4028 {
4029 int code = errno;
4030
4031 if (code == EAGAIN)
4032 return;
4033 #ifdef EWOULDBLOCK
4034 if (code == EWOULDBLOCK)
4035 return;
4036 #endif
4037
4038 if (!NILP (ps->log))
4039 call3 (ps->log, server, Qnil,
4040 concat3 (build_string ("accept failed with code"),
4041 Fnumber_to_string (make_number (code)),
4042 build_string ("\n")));
4043 return;
4044 }
4045
4046 connect_counter++;
4047
4048 /* Setup a new process to handle the connection. */
4049
4050 /* Generate a unique identification of the caller, and build contact
4051 information for this process. */
4052 host = Qt;
4053 service = Qnil;
4054 switch (saddr.sa.sa_family)
4055 {
4056 case AF_INET:
4057 {
4058 Lisp_Object args[5];
4059 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4060 args[0] = build_string ("%d.%d.%d.%d");
4061 args[1] = make_number (*ip++);
4062 args[2] = make_number (*ip++);
4063 args[3] = make_number (*ip++);
4064 args[4] = make_number (*ip++);
4065 host = Fformat (5, args);
4066 service = make_number (ntohs (saddr.in.sin_port));
4067
4068 args[0] = build_string (" <%s:%d>");
4069 args[1] = host;
4070 args[2] = service;
4071 caller = Fformat (3, args);
4072 }
4073 break;
4074
4075 #ifdef AF_INET6
4076 case AF_INET6:
4077 {
4078 Lisp_Object args[9];
4079 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4080 int i;
4081 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4082 for (i = 0; i < 8; i++)
4083 args[i+1] = make_number (ntohs (ip6[i]));
4084 host = Fformat (9, args);
4085 service = make_number (ntohs (saddr.in.sin_port));
4086
4087 args[0] = build_string (" <[%s]:%d>");
4088 args[1] = host;
4089 args[2] = service;
4090 caller = Fformat (3, args);
4091 }
4092 break;
4093 #endif
4094
4095 #ifdef HAVE_LOCAL_SOCKETS
4096 case AF_LOCAL:
4097 #endif
4098 default:
4099 caller = Fnumber_to_string (make_number (connect_counter));
4100 caller = concat3 (build_string (" <"), caller, build_string (">"));
4101 break;
4102 }
4103
4104 /* Create a new buffer name for this process if it doesn't have a
4105 filter. The new buffer name is based on the buffer name or
4106 process name of the server process concatenated with the caller
4107 identification. */
4108
4109 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4110 buffer = Qnil;
4111 else
4112 {
4113 buffer = ps->buffer;
4114 if (!NILP (buffer))
4115 buffer = Fbuffer_name (buffer);
4116 else
4117 buffer = ps->name;
4118 if (!NILP (buffer))
4119 {
4120 buffer = concat2 (buffer, caller);
4121 buffer = Fget_buffer_create (buffer);
4122 }
4123 }
4124
4125 /* Generate a unique name for the new server process. Combine the
4126 server process name with the caller identification. */
4127
4128 name = concat2 (ps->name, caller);
4129 proc = make_process (name);
4130
4131 chan_process[s] = proc;
4132
4133 #ifdef O_NONBLOCK
4134 fcntl (s, F_SETFL, O_NONBLOCK);
4135 #else
4136 #ifdef O_NDELAY
4137 fcntl (s, F_SETFL, O_NDELAY);
4138 #endif
4139 #endif
4140
4141 p = XPROCESS (proc);
4142
4143 /* Build new contact information for this setup. */
4144 contact = Fcopy_sequence (ps->childp);
4145 contact = Fplist_put (contact, QCserver, Qnil);
4146 contact = Fplist_put (contact, QChost, host);
4147 if (!NILP (service))
4148 contact = Fplist_put (contact, QCservice, service);
4149 contact = Fplist_put (contact, QCremote,
4150 conv_sockaddr_to_lisp (&saddr.sa, len));
4151 #ifdef HAVE_GETSOCKNAME
4152 len = sizeof saddr;
4153 if (getsockname (s, &saddr.sa, &len) == 0)
4154 contact = Fplist_put (contact, QClocal,
4155 conv_sockaddr_to_lisp (&saddr.sa, len));
4156 #endif
4157
4158 p->childp = contact;
4159 p->plist = Fcopy_sequence (ps->plist);
4160 p->type = Qnetwork;
4161
4162 p->buffer = buffer;
4163 p->sentinel = ps->sentinel;
4164 p->filter = ps->filter;
4165 p->command = Qnil;
4166 p->pid = 0;
4167 p->infd = s;
4168 p->outfd = s;
4169 p->status = Qrun;
4170
4171 /* Client processes for accepted connections are not stopped initially. */
4172 if (!EQ (p->filter, Qt))
4173 {
4174 FD_SET (s, &input_wait_mask);
4175 FD_SET (s, &non_keyboard_wait_mask);
4176 }
4177
4178 if (s > max_process_desc)
4179 max_process_desc = s;
4180
4181 /* Setup coding system for new process based on server process.
4182 This seems to be the proper thing to do, as the coding system
4183 of the new process should reflect the settings at the time the
4184 server socket was opened; not the current settings. */
4185
4186 p->decode_coding_system = ps->decode_coding_system;
4187 p->encode_coding_system = ps->encode_coding_system;
4188 setup_process_coding_systems (proc);
4189
4190 p->decoding_buf = empty_unibyte_string;
4191 p->decoding_carryover = 0;
4192 p->encoding_buf = empty_unibyte_string;
4193
4194 p->inherit_coding_system_flag
4195 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4196
4197 if (!NILP (ps->log))
4198 call3 (ps->log, server, proc,
4199 concat3 (build_string ("accept from "),
4200 (STRINGP (host) ? host : build_string ("-")),
4201 build_string ("\n")));
4202
4203 if (!NILP (p->sentinel))
4204 exec_sentinel (proc,
4205 concat3 (build_string ("open from "),
4206 (STRINGP (host) ? host : build_string ("-")),
4207 build_string ("\n")));
4208 }
4209
4210 /* This variable is different from waiting_for_input in keyboard.c.
4211 It is used to communicate to a lisp process-filter/sentinel (via the
4212 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4213 for user-input when that process-filter was called.
4214 waiting_for_input cannot be used as that is by definition 0 when
4215 lisp code is being evalled.
4216 This is also used in record_asynch_buffer_change.
4217 For that purpose, this must be 0
4218 when not inside wait_reading_process_output. */
4219 static int waiting_for_user_input_p;
4220
4221 static Lisp_Object
4222 wait_reading_process_output_unwind (Lisp_Object data)
4223 {
4224 waiting_for_user_input_p = XINT (data);
4225 return Qnil;
4226 }
4227
4228 /* This is here so breakpoints can be put on it. */
4229 static void
4230 wait_reading_process_output_1 (void)
4231 {
4232 }
4233
4234 /* Read and dispose of subprocess output while waiting for timeout to
4235 elapse and/or keyboard input to be available.
4236
4237 TIME_LIMIT is:
4238 timeout in seconds
4239 If negative, gobble data immediately available but don't wait for any.
4240
4241 NSECS is:
4242 an additional duration to wait, measured in nanoseconds
4243 If TIME_LIMIT is zero, then:
4244 If NSECS == 0, there is no limit.
4245 If NSECS > 0, the timeout consists of NSECS only.
4246 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4247
4248 READ_KBD is a lisp value:
4249 0 to ignore keyboard input, or
4250 1 to return when input is available, or
4251 -1 meaning caller will actually read the input, so don't throw to
4252 the quit handler, or
4253
4254 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4255 output that arrives.
4256
4257 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4258 (and gobble terminal input into the buffer if any arrives).
4259
4260 If WAIT_PROC is specified, wait until something arrives from that
4261 process. The return value is true if we read some input from
4262 that process.
4263
4264 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4265 (suspending output from other processes). A negative value
4266 means don't run any timers either.
4267
4268 If WAIT_PROC is specified, then the function returns true if we
4269 received input from that process before the timeout elapsed.
4270 Otherwise, return true if we received input from any process. */
4271
4272 int
4273 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4274 int do_display,
4275 Lisp_Object wait_for_cell,
4276 struct Lisp_Process *wait_proc, int just_wait_proc)
4277 {
4278 register int channel, nfds;
4279 SELECT_TYPE Available;
4280 SELECT_TYPE Writeok;
4281 int check_write;
4282 int check_delay, no_avail;
4283 int xerrno;
4284 Lisp_Object proc;
4285 EMACS_TIME timeout, end_time;
4286 int wait_channel = -1;
4287 int got_some_input = 0;
4288 ptrdiff_t count = SPECPDL_INDEX ();
4289
4290 FD_ZERO (&Available);
4291 FD_ZERO (&Writeok);
4292
4293 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4294 && !(CONSP (wait_proc->status) && EQ (XCAR (wait_proc->status), Qexit)))
4295 message ("Blocking call to accept-process-output with quit inhibited!!");
4296
4297 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4298 if (wait_proc != NULL)
4299 wait_channel = wait_proc->infd;
4300
4301 record_unwind_protect (wait_reading_process_output_unwind,
4302 make_number (waiting_for_user_input_p));
4303 waiting_for_user_input_p = read_kbd;
4304
4305 if (time_limit < 0)
4306 {
4307 time_limit = 0;
4308 nsecs = -1;
4309 }
4310 else if (TYPE_MAXIMUM (time_t) < time_limit)
4311 time_limit = TYPE_MAXIMUM (time_t);
4312
4313 /* Since we may need to wait several times,
4314 compute the absolute time to return at. */
4315 if (time_limit || nsecs) /* FIXME neither should be negative, no? */
4316 {
4317 EMACS_GET_TIME (end_time);
4318 EMACS_SET_SECS_NSECS (timeout, time_limit, nsecs);
4319 EMACS_ADD_TIME (end_time, end_time, timeout);
4320 }
4321
4322 while (1)
4323 {
4324 int timeout_reduced_for_timers = 0;
4325
4326 /* If calling from keyboard input, do not quit
4327 since we want to return C-g as an input character.
4328 Otherwise, do pending quit if requested. */
4329 if (read_kbd >= 0)
4330 QUIT;
4331 #ifdef SYNC_INPUT
4332 else
4333 process_pending_signals ();
4334 #endif
4335
4336 /* Exit now if the cell we're waiting for became non-nil. */
4337 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4338 break;
4339
4340 /* Compute time from now till when time limit is up */
4341 /* Exit if already run out */
4342 if (nsecs < 0)
4343 {
4344 /* -1 specified for timeout means
4345 gobble output available now
4346 but don't wait at all. */
4347
4348 EMACS_SET_SECS_USECS (timeout, 0, 0);
4349 }
4350 else if (time_limit || nsecs)
4351 {
4352 EMACS_GET_TIME (timeout);
4353 if (EMACS_TIME_LE (end_time, timeout))
4354 break;
4355 EMACS_SUB_TIME (timeout, end_time, timeout);
4356 }
4357 else
4358 {
4359 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4360 }
4361
4362 /* Normally we run timers here.
4363 But not if wait_for_cell; in those cases,
4364 the wait is supposed to be short,
4365 and those callers cannot handle running arbitrary Lisp code here. */
4366 if (NILP (wait_for_cell)
4367 && just_wait_proc >= 0)
4368 {
4369 EMACS_TIME timer_delay;
4370
4371 do
4372 {
4373 int old_timers_run = timers_run;
4374 struct buffer *old_buffer = current_buffer;
4375 Lisp_Object old_window = selected_window;
4376
4377 timer_delay = timer_check ();
4378
4379 /* If a timer has run, this might have changed buffers
4380 an alike. Make read_key_sequence aware of that. */
4381 if (timers_run != old_timers_run
4382 && (old_buffer != current_buffer
4383 || !EQ (old_window, selected_window))
4384 && waiting_for_user_input_p == -1)
4385 record_asynch_buffer_change ();
4386
4387 if (timers_run != old_timers_run && do_display)
4388 /* We must retry, since a timer may have requeued itself
4389 and that could alter the time_delay. */
4390 redisplay_preserve_echo_area (9);
4391 else
4392 break;
4393 }
4394 while (!detect_input_pending ());
4395
4396 /* If there is unread keyboard input, also return. */
4397 if (read_kbd != 0
4398 && requeued_events_pending_p ())
4399 break;
4400
4401 /* If time_limit is negative, we are not going to wait at all. */
4402 if (0 <= nsecs)
4403 {
4404 if (EMACS_TIME_VALID_P (timer_delay))
4405 {
4406 if (EMACS_TIME_LT (timer_delay, timeout))
4407 {
4408 timeout = timer_delay;
4409 timeout_reduced_for_timers = 1;
4410 }
4411 }
4412 else
4413 {
4414 /* This is so a breakpoint can be put here. */
4415 wait_reading_process_output_1 ();
4416 }
4417 }
4418 }
4419
4420 /* Cause C-g and alarm signals to take immediate action,
4421 and cause input available signals to zero out timeout.
4422
4423 It is important that we do this before checking for process
4424 activity. If we get a SIGCHLD after the explicit checks for
4425 process activity, timeout is the only way we will know. */
4426 if (read_kbd < 0)
4427 set_waiting_for_input (&timeout);
4428
4429 /* If status of something has changed, and no input is
4430 available, notify the user of the change right away. After
4431 this explicit check, we'll let the SIGCHLD handler zap
4432 timeout to get our attention. */
4433 if (update_tick != process_tick)
4434 {
4435 SELECT_TYPE Atemp;
4436 SELECT_TYPE Ctemp;
4437
4438 if (kbd_on_hold_p ())
4439 FD_ZERO (&Atemp);
4440 else
4441 Atemp = input_wait_mask;
4442 Ctemp = write_mask;
4443
4444 EMACS_SET_SECS_USECS (timeout, 0, 0);
4445 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4446 &Atemp,
4447 #ifdef NON_BLOCKING_CONNECT
4448 (num_pending_connects > 0 ? &Ctemp : NULL),
4449 #else
4450 NULL,
4451 #endif
4452 NULL, &timeout, NULL)
4453 <= 0))
4454 {
4455 /* It's okay for us to do this and then continue with
4456 the loop, since timeout has already been zeroed out. */
4457 clear_waiting_for_input ();
4458 status_notify (NULL);
4459 if (do_display) redisplay_preserve_echo_area (13);
4460 }
4461 }
4462
4463 /* Don't wait for output from a non-running process. Just
4464 read whatever data has already been received. */
4465 if (wait_proc && wait_proc->raw_status_new)
4466 update_status (wait_proc);
4467 if (wait_proc
4468 && ! EQ (wait_proc->status, Qrun)
4469 && ! EQ (wait_proc->status, Qconnect))
4470 {
4471 int nread, total_nread = 0;
4472
4473 clear_waiting_for_input ();
4474 XSETPROCESS (proc, wait_proc);
4475
4476 /* Read data from the process, until we exhaust it. */
4477 while (wait_proc->infd >= 0)
4478 {
4479 nread = read_process_output (proc, wait_proc->infd);
4480
4481 if (nread == 0)
4482 break;
4483
4484 if (0 < nread)
4485 {
4486 total_nread += nread;
4487 got_some_input = 1;
4488 }
4489 #ifdef EIO
4490 else if (nread == -1 && EIO == errno)
4491 break;
4492 #endif
4493 #ifdef EAGAIN
4494 else if (nread == -1 && EAGAIN == errno)
4495 break;
4496 #endif
4497 #ifdef EWOULDBLOCK
4498 else if (nread == -1 && EWOULDBLOCK == errno)
4499 break;
4500 #endif
4501 }
4502 if (total_nread > 0 && do_display)
4503 redisplay_preserve_echo_area (10);
4504
4505 break;
4506 }
4507
4508 /* Wait till there is something to do */
4509
4510 if (wait_proc && just_wait_proc)
4511 {
4512 if (wait_proc->infd < 0) /* Terminated */
4513 break;
4514 FD_SET (wait_proc->infd, &Available);
4515 check_delay = 0;
4516 check_write = 0;
4517 }
4518 else if (!NILP (wait_for_cell))
4519 {
4520 Available = non_process_wait_mask;
4521 check_delay = 0;
4522 check_write = 0;
4523 }
4524 else
4525 {
4526 if (! read_kbd)
4527 Available = non_keyboard_wait_mask;
4528 else
4529 Available = input_wait_mask;
4530 Writeok = write_mask;
4531 #ifdef SELECT_CANT_DO_WRITE_MASK
4532 check_write = 0;
4533 #else
4534 check_write = 1;
4535 #endif
4536 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4537 }
4538
4539 /* If frame size has changed or the window is newly mapped,
4540 redisplay now, before we start to wait. There is a race
4541 condition here; if a SIGIO arrives between now and the select
4542 and indicates that a frame is trashed, the select may block
4543 displaying a trashed screen. */
4544 if (frame_garbaged && do_display)
4545 {
4546 clear_waiting_for_input ();
4547 redisplay_preserve_echo_area (11);
4548 if (read_kbd < 0)
4549 set_waiting_for_input (&timeout);
4550 }
4551
4552 /* Skip the `select' call if input is available and we're
4553 waiting for keyboard input or a cell change (which can be
4554 triggered by processing X events). In the latter case, set
4555 nfds to 1 to avoid breaking the loop. */
4556 no_avail = 0;
4557 if ((read_kbd || !NILP (wait_for_cell))
4558 && detect_input_pending ())
4559 {
4560 nfds = read_kbd ? 0 : 1;
4561 no_avail = 1;
4562 }
4563
4564 if (!no_avail)
4565 {
4566
4567 #ifdef ADAPTIVE_READ_BUFFERING
4568 /* Set the timeout for adaptive read buffering if any
4569 process has non-zero read_output_skip and non-zero
4570 read_output_delay, and we are not reading output for a
4571 specific wait_channel. It is not executed if
4572 Vprocess_adaptive_read_buffering is nil. */
4573 if (process_output_skip && check_delay > 0)
4574 {
4575 int nsecs = EMACS_NSECS (timeout);
4576 if (EMACS_SECS (timeout) > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4577 nsecs = READ_OUTPUT_DELAY_MAX;
4578 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4579 {
4580 proc = chan_process[channel];
4581 if (NILP (proc))
4582 continue;
4583 /* Find minimum non-zero read_output_delay among the
4584 processes with non-zero read_output_skip. */
4585 if (XPROCESS (proc)->read_output_delay > 0)
4586 {
4587 check_delay--;
4588 if (!XPROCESS (proc)->read_output_skip)
4589 continue;
4590 FD_CLR (channel, &Available);
4591 XPROCESS (proc)->read_output_skip = 0;
4592 if (XPROCESS (proc)->read_output_delay < nsecs)
4593 nsecs = XPROCESS (proc)->read_output_delay;
4594 }
4595 }
4596 EMACS_SET_SECS_NSECS (timeout, 0, nsecs);
4597 process_output_skip = 0;
4598 }
4599 #endif
4600 #if defined (USE_GTK) || defined (HAVE_GCONF) || defined (HAVE_GSETTINGS)
4601 nfds = xg_select
4602 #elif defined (HAVE_NS)
4603 nfds = ns_select
4604 #else
4605 nfds = pselect
4606 #endif
4607 (max (max_process_desc, max_input_desc) + 1,
4608 &Available,
4609 (check_write ? &Writeok : (SELECT_TYPE *)0),
4610 NULL, &timeout, NULL);
4611
4612 #ifdef HAVE_GNUTLS
4613 /* GnuTLS buffers data internally. In lowat mode it leaves
4614 some data in the TCP buffers so that select works, but
4615 with custom pull/push functions we need to check if some
4616 data is available in the buffers manually. */
4617 if (nfds == 0)
4618 {
4619 if (! wait_proc)
4620 {
4621 /* We're not waiting on a specific process, so loop
4622 through all the channels and check for data.
4623 This is a workaround needed for some versions of
4624 the gnutls library -- 2.12.14 has been confirmed
4625 to need it. See
4626 http://comments.gmane.org/gmane.emacs.devel/145074 */
4627 for (channel = 0; channel < MAXDESC; ++channel)
4628 if (! NILP (chan_process[channel]))
4629 {
4630 struct Lisp_Process *p =
4631 XPROCESS (chan_process[channel]);
4632 if (p && p->gnutls_p && p->infd
4633 && ((emacs_gnutls_record_check_pending
4634 (p->gnutls_state))
4635 > 0))
4636 {
4637 nfds++;
4638 FD_SET (p->infd, &Available);
4639 }
4640 }
4641 }
4642 else
4643 {
4644 /* Check this specific channel. */
4645 if (wait_proc->gnutls_p /* Check for valid process. */
4646 /* Do we have pending data? */
4647 && ((emacs_gnutls_record_check_pending
4648 (wait_proc->gnutls_state))
4649 > 0))
4650 {
4651 nfds = 1;
4652 /* Set to Available. */
4653 FD_SET (wait_proc->infd, &Available);
4654 }
4655 }
4656 }
4657 #endif
4658 }
4659
4660 xerrno = errno;
4661
4662 /* Make C-g and alarm signals set flags again */
4663 clear_waiting_for_input ();
4664
4665 /* If we woke up due to SIGWINCH, actually change size now. */
4666 do_pending_window_change (0);
4667
4668 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4669 /* We wanted the full specified time, so return now. */
4670 break;
4671 if (nfds < 0)
4672 {
4673 if (xerrno == EINTR)
4674 no_avail = 1;
4675 else if (xerrno == EBADF)
4676 {
4677 #ifdef AIX
4678 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4679 the child's closure of the pts gives the parent a SIGHUP, and
4680 the ptc file descriptor is automatically closed,
4681 yielding EBADF here or at select() call above.
4682 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4683 in m/ibmrt-aix.h), and here we just ignore the select error.
4684 Cleanup occurs c/o status_notify after SIGCLD. */
4685 no_avail = 1; /* Cannot depend on values returned */
4686 #else
4687 abort ();
4688 #endif
4689 }
4690 else
4691 error ("select error: %s", emacs_strerror (xerrno));
4692 }
4693
4694 if (no_avail)
4695 {
4696 FD_ZERO (&Available);
4697 check_write = 0;
4698 }
4699
4700 #if 0 /* When polling is used, interrupt_input is 0,
4701 so get_input_pending should read the input.
4702 So this should not be needed. */
4703 /* If we are using polling for input,
4704 and we see input available, make it get read now.
4705 Otherwise it might not actually get read for a second.
4706 And on hpux, since we turn off polling in wait_reading_process_output,
4707 it might never get read at all if we don't spend much time
4708 outside of wait_reading_process_output. */
4709 if (read_kbd && interrupt_input
4710 && keyboard_bit_set (&Available)
4711 && input_polling_used ())
4712 kill (getpid (), SIGALRM);
4713 #endif
4714
4715 /* Check for keyboard input */
4716 /* If there is any, return immediately
4717 to give it higher priority than subprocesses */
4718
4719 if (read_kbd != 0)
4720 {
4721 int old_timers_run = timers_run;
4722 struct buffer *old_buffer = current_buffer;
4723 Lisp_Object old_window = selected_window;
4724 int leave = 0;
4725
4726 if (detect_input_pending_run_timers (do_display))
4727 {
4728 swallow_events (do_display);
4729 if (detect_input_pending_run_timers (do_display))
4730 leave = 1;
4731 }
4732
4733 /* If a timer has run, this might have changed buffers
4734 an alike. Make read_key_sequence aware of that. */
4735 if (timers_run != old_timers_run
4736 && waiting_for_user_input_p == -1
4737 && (old_buffer != current_buffer
4738 || !EQ (old_window, selected_window)))
4739 record_asynch_buffer_change ();
4740
4741 if (leave)
4742 break;
4743 }
4744
4745 /* If there is unread keyboard input, also return. */
4746 if (read_kbd != 0
4747 && requeued_events_pending_p ())
4748 break;
4749
4750 /* If we are not checking for keyboard input now,
4751 do process events (but don't run any timers).
4752 This is so that X events will be processed.
4753 Otherwise they may have to wait until polling takes place.
4754 That would causes delays in pasting selections, for example.
4755
4756 (We used to do this only if wait_for_cell.) */
4757 if (read_kbd == 0 && detect_input_pending ())
4758 {
4759 swallow_events (do_display);
4760 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4761 if (detect_input_pending ())
4762 break;
4763 #endif
4764 }
4765
4766 /* Exit now if the cell we're waiting for became non-nil. */
4767 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4768 break;
4769
4770 #ifdef SIGIO
4771 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4772 go read it. This can happen with X on BSD after logging out.
4773 In that case, there really is no input and no SIGIO,
4774 but select says there is input. */
4775
4776 if (read_kbd && interrupt_input
4777 && keyboard_bit_set (&Available) && ! noninteractive)
4778 kill (getpid (), SIGIO);
4779 #endif
4780
4781 if (! wait_proc)
4782 got_some_input |= nfds > 0;
4783
4784 /* If checking input just got us a size-change event from X,
4785 obey it now if we should. */
4786 if (read_kbd || ! NILP (wait_for_cell))
4787 do_pending_window_change (0);
4788
4789 /* Check for data from a process. */
4790 if (no_avail || nfds == 0)
4791 continue;
4792
4793 for (channel = 0; channel <= max_input_desc; ++channel)
4794 {
4795 struct fd_callback_data *d = &fd_callback_info[channel];
4796 if (FD_ISSET (channel, &Available)
4797 && d->func != 0
4798 && (d->condition & FOR_READ) != 0)
4799 d->func (channel, d->data, 1);
4800 if (FD_ISSET (channel, &write_mask)
4801 && d->func != 0
4802 && (d->condition & FOR_WRITE) != 0)
4803 d->func (channel, d->data, 0);
4804 }
4805
4806 for (channel = 0; channel <= max_process_desc; channel++)
4807 {
4808 if (FD_ISSET (channel, &Available)
4809 && FD_ISSET (channel, &non_keyboard_wait_mask)
4810 && !FD_ISSET (channel, &non_process_wait_mask))
4811 {
4812 int nread;
4813
4814 /* If waiting for this channel, arrange to return as
4815 soon as no more input to be processed. No more
4816 waiting. */
4817 if (wait_channel == channel)
4818 {
4819 wait_channel = -1;
4820 nsecs = -1;
4821 got_some_input = 1;
4822 }
4823 proc = chan_process[channel];
4824 if (NILP (proc))
4825 continue;
4826
4827 /* If this is a server stream socket, accept connection. */
4828 if (EQ (XPROCESS (proc)->status, Qlisten))
4829 {
4830 server_accept_connection (proc, channel);
4831 continue;
4832 }
4833
4834 /* Read data from the process, starting with our
4835 buffered-ahead character if we have one. */
4836
4837 nread = read_process_output (proc, channel);
4838 if (nread > 0)
4839 {
4840 /* Since read_process_output can run a filter,
4841 which can call accept-process-output,
4842 don't try to read from any other processes
4843 before doing the select again. */
4844 FD_ZERO (&Available);
4845
4846 if (do_display)
4847 redisplay_preserve_echo_area (12);
4848 }
4849 #ifdef EWOULDBLOCK
4850 else if (nread == -1 && errno == EWOULDBLOCK)
4851 ;
4852 #endif
4853 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4854 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4855 #ifdef O_NONBLOCK
4856 else if (nread == -1 && errno == EAGAIN)
4857 ;
4858 #else
4859 #ifdef O_NDELAY
4860 else if (nread == -1 && errno == EAGAIN)
4861 ;
4862 /* Note that we cannot distinguish between no input
4863 available now and a closed pipe.
4864 With luck, a closed pipe will be accompanied by
4865 subprocess termination and SIGCHLD. */
4866 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4867 ;
4868 #endif /* O_NDELAY */
4869 #endif /* O_NONBLOCK */
4870 #ifdef HAVE_PTYS
4871 /* On some OSs with ptys, when the process on one end of
4872 a pty exits, the other end gets an error reading with
4873 errno = EIO instead of getting an EOF (0 bytes read).
4874 Therefore, if we get an error reading and errno =
4875 EIO, just continue, because the child process has
4876 exited and should clean itself up soon (e.g. when we
4877 get a SIGCHLD).
4878
4879 However, it has been known to happen that the SIGCHLD
4880 got lost. So raise the signal again just in case.
4881 It can't hurt. */
4882 else if (nread == -1 && errno == EIO)
4883 {
4884 struct Lisp_Process *p = XPROCESS (proc);
4885
4886 /* Clear the descriptor now, so we only raise the
4887 signal once. */
4888 FD_CLR (channel, &input_wait_mask);
4889 FD_CLR (channel, &non_keyboard_wait_mask);
4890
4891 if (p->pid == -2)
4892 {
4893 /* If the EIO occurs on a pty, sigchld_handler's
4894 wait3() will not find the process object to
4895 delete. Do it here. */
4896 p->tick = ++process_tick;
4897 p->status = Qfailed;
4898 }
4899 else
4900 kill (getpid (), SIGCHLD);
4901 }
4902 #endif /* HAVE_PTYS */
4903 /* If we can detect process termination, don't consider the
4904 process gone just because its pipe is closed. */
4905 #ifdef SIGCHLD
4906 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4907 ;
4908 #endif
4909 else
4910 {
4911 /* Preserve status of processes already terminated. */
4912 XPROCESS (proc)->tick = ++process_tick;
4913 deactivate_process (proc);
4914 if (XPROCESS (proc)->raw_status_new)
4915 update_status (XPROCESS (proc));
4916 if (EQ (XPROCESS (proc)->status, Qrun))
4917 XPROCESS (proc)->status
4918 = Fcons (Qexit, Fcons (make_number (256), Qnil));
4919 }
4920 }
4921 #ifdef NON_BLOCKING_CONNECT
4922 if (FD_ISSET (channel, &Writeok)
4923 && FD_ISSET (channel, &connect_wait_mask))
4924 {
4925 struct Lisp_Process *p;
4926
4927 FD_CLR (channel, &connect_wait_mask);
4928 FD_CLR (channel, &write_mask);
4929 if (--num_pending_connects < 0)
4930 abort ();
4931
4932 proc = chan_process[channel];
4933 if (NILP (proc))
4934 continue;
4935
4936 p = XPROCESS (proc);
4937
4938 #ifdef GNU_LINUX
4939 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4940 So only use it on systems where it is known to work. */
4941 {
4942 socklen_t xlen = sizeof (xerrno);
4943 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4944 xerrno = errno;
4945 }
4946 #else
4947 {
4948 struct sockaddr pname;
4949 int pnamelen = sizeof (pname);
4950
4951 /* If connection failed, getpeername will fail. */
4952 xerrno = 0;
4953 if (getpeername (channel, &pname, &pnamelen) < 0)
4954 {
4955 /* Obtain connect failure code through error slippage. */
4956 char dummy;
4957 xerrno = errno;
4958 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4959 xerrno = errno;
4960 }
4961 }
4962 #endif
4963 if (xerrno)
4964 {
4965 p->tick = ++process_tick;
4966 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
4967 deactivate_process (proc);
4968 }
4969 else
4970 {
4971 p->status = Qrun;
4972 /* Execute the sentinel here. If we had relied on
4973 status_notify to do it later, it will read input
4974 from the process before calling the sentinel. */
4975 exec_sentinel (proc, build_string ("open\n"));
4976 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4977 {
4978 FD_SET (p->infd, &input_wait_mask);
4979 FD_SET (p->infd, &non_keyboard_wait_mask);
4980 }
4981 }
4982 }
4983 #endif /* NON_BLOCKING_CONNECT */
4984 } /* end for each file descriptor */
4985 } /* end while exit conditions not met */
4986
4987 unbind_to (count, Qnil);
4988
4989 /* If calling from keyboard input, do not quit
4990 since we want to return C-g as an input character.
4991 Otherwise, do pending quit if requested. */
4992 if (read_kbd >= 0)
4993 {
4994 /* Prevent input_pending from remaining set if we quit. */
4995 clear_input_pending ();
4996 QUIT;
4997 }
4998
4999 return got_some_input;
5000 }
5001 \f
5002 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5003
5004 static Lisp_Object
5005 read_process_output_call (Lisp_Object fun_and_args)
5006 {
5007 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5008 }
5009
5010 static Lisp_Object
5011 read_process_output_error_handler (Lisp_Object error_val)
5012 {
5013 cmd_error_internal (error_val, "error in process filter: ");
5014 Vinhibit_quit = Qt;
5015 update_echo_area ();
5016 Fsleep_for (make_number (2), Qnil);
5017 return Qt;
5018 }
5019
5020 /* Read pending output from the process channel,
5021 starting with our buffered-ahead character if we have one.
5022 Yield number of decoded characters read.
5023
5024 This function reads at most 4096 characters.
5025 If you want to read all available subprocess output,
5026 you must call it repeatedly until it returns zero.
5027
5028 The characters read are decoded according to PROC's coding-system
5029 for decoding. */
5030
5031 static int
5032 read_process_output (Lisp_Object proc, register int channel)
5033 {
5034 register ssize_t nbytes;
5035 char *chars;
5036 register Lisp_Object outstream;
5037 register struct Lisp_Process *p = XPROCESS (proc);
5038 register ptrdiff_t opoint;
5039 struct coding_system *coding = proc_decode_coding_system[channel];
5040 int carryover = p->decoding_carryover;
5041 int readmax = 4096;
5042 ptrdiff_t count = SPECPDL_INDEX ();
5043 Lisp_Object odeactivate;
5044
5045 chars = (char *) alloca (carryover + readmax);
5046 if (carryover)
5047 /* See the comment above. */
5048 memcpy (chars, SDATA (p->decoding_buf), carryover);
5049
5050 #ifdef DATAGRAM_SOCKETS
5051 /* We have a working select, so proc_buffered_char is always -1. */
5052 if (DATAGRAM_CHAN_P (channel))
5053 {
5054 socklen_t len = datagram_address[channel].len;
5055 nbytes = recvfrom (channel, chars + carryover, readmax,
5056 0, datagram_address[channel].sa, &len);
5057 }
5058 else
5059 #endif
5060 {
5061 int buffered = 0 <= proc_buffered_char[channel];
5062 if (buffered)
5063 {
5064 chars[carryover] = proc_buffered_char[channel];
5065 proc_buffered_char[channel] = -1;
5066 }
5067 #ifdef HAVE_GNUTLS
5068 if (p->gnutls_p)
5069 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
5070 readmax - buffered);
5071 else
5072 #endif
5073 nbytes = emacs_read (channel, chars + carryover + buffered,
5074 readmax - buffered);
5075 #ifdef ADAPTIVE_READ_BUFFERING
5076 if (nbytes > 0 && p->adaptive_read_buffering)
5077 {
5078 int delay = p->read_output_delay;
5079 if (nbytes < 256)
5080 {
5081 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5082 {
5083 if (delay == 0)
5084 process_output_delay_count++;
5085 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5086 }
5087 }
5088 else if (delay > 0 && nbytes == readmax - buffered)
5089 {
5090 delay -= READ_OUTPUT_DELAY_INCREMENT;
5091 if (delay == 0)
5092 process_output_delay_count--;
5093 }
5094 p->read_output_delay = delay;
5095 if (delay)
5096 {
5097 p->read_output_skip = 1;
5098 process_output_skip = 1;
5099 }
5100 }
5101 #endif
5102 nbytes += buffered;
5103 nbytes += buffered && nbytes <= 0;
5104 }
5105
5106 p->decoding_carryover = 0;
5107
5108 /* At this point, NBYTES holds number of bytes just received
5109 (including the one in proc_buffered_char[channel]). */
5110 if (nbytes <= 0)
5111 {
5112 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5113 return nbytes;
5114 coding->mode |= CODING_MODE_LAST_BLOCK;
5115 }
5116
5117 /* Now set NBYTES how many bytes we must decode. */
5118 nbytes += carryover;
5119
5120 odeactivate = Vdeactivate_mark;
5121 /* There's no good reason to let process filters change the current
5122 buffer, and many callers of accept-process-output, sit-for, and
5123 friends don't expect current-buffer to be changed from under them. */
5124 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
5125
5126 /* Read and dispose of the process output. */
5127 outstream = p->filter;
5128 if (!NILP (outstream))
5129 {
5130 Lisp_Object text;
5131 int outer_running_asynch_code = running_asynch_code;
5132 int waiting = waiting_for_user_input_p;
5133
5134 /* No need to gcpro these, because all we do with them later
5135 is test them for EQness, and none of them should be a string. */
5136 #if 0
5137 Lisp_Object obuffer, okeymap;
5138 XSETBUFFER (obuffer, current_buffer);
5139 okeymap = BVAR (current_buffer, keymap);
5140 #endif
5141
5142 /* We inhibit quit here instead of just catching it so that
5143 hitting ^G when a filter happens to be running won't screw
5144 it up. */
5145 specbind (Qinhibit_quit, Qt);
5146 specbind (Qlast_nonmenu_event, Qt);
5147
5148 /* In case we get recursively called,
5149 and we already saved the match data nonrecursively,
5150 save the same match data in safely recursive fashion. */
5151 if (outer_running_asynch_code)
5152 {
5153 Lisp_Object tem;
5154 /* Don't clobber the CURRENT match data, either! */
5155 tem = Fmatch_data (Qnil, Qnil, Qnil);
5156 restore_search_regs ();
5157 record_unwind_save_match_data ();
5158 Fset_match_data (tem, Qt);
5159 }
5160
5161 /* For speed, if a search happens within this code,
5162 save the match data in a special nonrecursive fashion. */
5163 running_asynch_code = 1;
5164
5165 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5166 text = coding->dst_object;
5167 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5168 /* A new coding system might be found. */
5169 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5170 {
5171 p->decode_coding_system = Vlast_coding_system_used;
5172
5173 /* Don't call setup_coding_system for
5174 proc_decode_coding_system[channel] here. It is done in
5175 detect_coding called via decode_coding above. */
5176
5177 /* If a coding system for encoding is not yet decided, we set
5178 it as the same as coding-system for decoding.
5179
5180 But, before doing that we must check if
5181 proc_encode_coding_system[p->outfd] surely points to a
5182 valid memory because p->outfd will be changed once EOF is
5183 sent to the process. */
5184 if (NILP (p->encode_coding_system)
5185 && proc_encode_coding_system[p->outfd])
5186 {
5187 p->encode_coding_system
5188 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5189 setup_coding_system (p->encode_coding_system,
5190 proc_encode_coding_system[p->outfd]);
5191 }
5192 }
5193
5194 if (coding->carryover_bytes > 0)
5195 {
5196 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5197 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5198 memcpy (SDATA (p->decoding_buf), coding->carryover,
5199 coding->carryover_bytes);
5200 p->decoding_carryover = coding->carryover_bytes;
5201 }
5202 if (SBYTES (text) > 0)
5203 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5204 sometimes it's simply wrong to wrap (e.g. when called from
5205 accept-process-output). */
5206 internal_condition_case_1 (read_process_output_call,
5207 Fcons (outstream,
5208 Fcons (proc, Fcons (text, Qnil))),
5209 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5210 read_process_output_error_handler);
5211
5212 /* If we saved the match data nonrecursively, restore it now. */
5213 restore_search_regs ();
5214 running_asynch_code = outer_running_asynch_code;
5215
5216 /* Restore waiting_for_user_input_p as it was
5217 when we were called, in case the filter clobbered it. */
5218 waiting_for_user_input_p = waiting;
5219
5220 #if 0 /* Call record_asynch_buffer_change unconditionally,
5221 because we might have changed minor modes or other things
5222 that affect key bindings. */
5223 if (! EQ (Fcurrent_buffer (), obuffer)
5224 || ! EQ (current_buffer->keymap, okeymap))
5225 #endif
5226 /* But do it only if the caller is actually going to read events.
5227 Otherwise there's no need to make him wake up, and it could
5228 cause trouble (for example it would make sit_for return). */
5229 if (waiting_for_user_input_p == -1)
5230 record_asynch_buffer_change ();
5231 }
5232
5233 /* If no filter, write into buffer if it isn't dead. */
5234 else if (!NILP (p->buffer) && !NILP (BVAR (XBUFFER (p->buffer), name)))
5235 {
5236 Lisp_Object old_read_only;
5237 ptrdiff_t old_begv, old_zv;
5238 ptrdiff_t old_begv_byte, old_zv_byte;
5239 ptrdiff_t before, before_byte;
5240 ptrdiff_t opoint_byte;
5241 Lisp_Object text;
5242 struct buffer *b;
5243
5244 Fset_buffer (p->buffer);
5245 opoint = PT;
5246 opoint_byte = PT_BYTE;
5247 old_read_only = BVAR (current_buffer, read_only);
5248 old_begv = BEGV;
5249 old_zv = ZV;
5250 old_begv_byte = BEGV_BYTE;
5251 old_zv_byte = ZV_BYTE;
5252
5253 BVAR (current_buffer, read_only) = Qnil;
5254
5255 /* Insert new output into buffer
5256 at the current end-of-output marker,
5257 thus preserving logical ordering of input and output. */
5258 if (XMARKER (p->mark)->buffer)
5259 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5260 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5261 ZV_BYTE));
5262 else
5263 SET_PT_BOTH (ZV, ZV_BYTE);
5264 before = PT;
5265 before_byte = PT_BYTE;
5266
5267 /* If the output marker is outside of the visible region, save
5268 the restriction and widen. */
5269 if (! (BEGV <= PT && PT <= ZV))
5270 Fwiden ();
5271
5272 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5273 text = coding->dst_object;
5274 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5275 /* A new coding system might be found. See the comment in the
5276 similar code in the previous `if' block. */
5277 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5278 {
5279 p->decode_coding_system = Vlast_coding_system_used;
5280 if (NILP (p->encode_coding_system)
5281 && proc_encode_coding_system[p->outfd])
5282 {
5283 p->encode_coding_system
5284 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5285 setup_coding_system (p->encode_coding_system,
5286 proc_encode_coding_system[p->outfd]);
5287 }
5288 }
5289 if (coding->carryover_bytes > 0)
5290 {
5291 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5292 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5293 memcpy (SDATA (p->decoding_buf), coding->carryover,
5294 coding->carryover_bytes);
5295 p->decoding_carryover = coding->carryover_bytes;
5296 }
5297 /* Adjust the multibyteness of TEXT to that of the buffer. */
5298 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5299 != ! STRING_MULTIBYTE (text))
5300 text = (STRING_MULTIBYTE (text)
5301 ? Fstring_as_unibyte (text)
5302 : Fstring_to_multibyte (text));
5303 /* Insert before markers in case we are inserting where
5304 the buffer's mark is, and the user's next command is Meta-y. */
5305 insert_from_string_before_markers (text, 0, 0,
5306 SCHARS (text), SBYTES (text), 0);
5307
5308 /* Make sure the process marker's position is valid when the
5309 process buffer is changed in the signal_after_change above.
5310 W3 is known to do that. */
5311 if (BUFFERP (p->buffer)
5312 && (b = XBUFFER (p->buffer), b != current_buffer))
5313 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5314 else
5315 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5316
5317 update_mode_lines++;
5318
5319 /* Make sure opoint and the old restrictions
5320 float ahead of any new text just as point would. */
5321 if (opoint >= before)
5322 {
5323 opoint += PT - before;
5324 opoint_byte += PT_BYTE - before_byte;
5325 }
5326 if (old_begv > before)
5327 {
5328 old_begv += PT - before;
5329 old_begv_byte += PT_BYTE - before_byte;
5330 }
5331 if (old_zv >= before)
5332 {
5333 old_zv += PT - before;
5334 old_zv_byte += PT_BYTE - before_byte;
5335 }
5336
5337 /* If the restriction isn't what it should be, set it. */
5338 if (old_begv != BEGV || old_zv != ZV)
5339 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5340
5341
5342 BVAR (current_buffer, read_only) = old_read_only;
5343 SET_PT_BOTH (opoint, opoint_byte);
5344 }
5345 /* Handling the process output should not deactivate the mark. */
5346 Vdeactivate_mark = odeactivate;
5347
5348 unbind_to (count, Qnil);
5349 return nbytes;
5350 }
5351 \f
5352 /* Sending data to subprocess */
5353
5354 static jmp_buf send_process_frame;
5355 static Lisp_Object process_sent_to;
5356
5357 #ifndef FORWARD_SIGNAL_TO_MAIN_THREAD
5358 static _Noreturn void send_process_trap (int);
5359 #endif
5360
5361 static void
5362 send_process_trap (int ignore)
5363 {
5364 SIGNAL_THREAD_CHECK (SIGPIPE);
5365 sigunblock (sigmask (SIGPIPE));
5366 longjmp (send_process_frame, 1);
5367 }
5368
5369 /* In send_process, when a write fails temporarily,
5370 wait_reading_process_output is called. It may execute user code,
5371 e.g. timers, that attempts to write new data to the same process.
5372 We must ensure that data is sent in the right order, and not
5373 interspersed half-completed with other writes (Bug#10815). This is
5374 handled by the write_queue element of struct process. It is a list
5375 with each entry having the form
5376
5377 (string . (offset . length))
5378
5379 where STRING is a lisp string, OFFSET is the offset into the
5380 string's byte sequence from which we should begin to send, and
5381 LENGTH is the number of bytes left to send. */
5382
5383 /* Create a new entry in write_queue.
5384 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5385 BUF is a pointer to the string sequence of the input_obj or a C
5386 string in case of Qt or Qnil. */
5387
5388 static void
5389 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5390 const char *buf, ptrdiff_t len, int front)
5391 {
5392 ptrdiff_t offset;
5393 Lisp_Object entry, obj;
5394
5395 if (STRINGP (input_obj))
5396 {
5397 offset = buf - SSDATA (input_obj);
5398 obj = input_obj;
5399 }
5400 else
5401 {
5402 offset = 0;
5403 obj = make_unibyte_string (buf, len);
5404 }
5405
5406 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5407
5408 if (front)
5409 p->write_queue = Fcons (entry, p->write_queue);
5410 else
5411 p->write_queue = nconc2 (p->write_queue, Fcons (entry, Qnil));
5412 }
5413
5414 /* Remove the first element in the write_queue of process P, put its
5415 contents in OBJ, BUF and LEN, and return non-zero. If the
5416 write_queue is empty, return zero. */
5417
5418 static int
5419 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5420 const char **buf, ptrdiff_t *len)
5421 {
5422 Lisp_Object entry, offset_length;
5423 ptrdiff_t offset;
5424
5425 if (NILP (p->write_queue))
5426 return 0;
5427
5428 entry = XCAR (p->write_queue);
5429 p->write_queue = XCDR (p->write_queue);
5430
5431 *obj = XCAR (entry);
5432 offset_length = XCDR (entry);
5433
5434 *len = XINT (XCDR (offset_length));
5435 offset = XINT (XCAR (offset_length));
5436 *buf = SSDATA (*obj) + offset;
5437
5438 return 1;
5439 }
5440
5441 /* Send some data to process PROC.
5442 BUF is the beginning of the data; LEN is the number of characters.
5443 OBJECT is the Lisp object that the data comes from. If OBJECT is
5444 nil or t, it means that the data comes from C string.
5445
5446 If OBJECT is not nil, the data is encoded by PROC's coding-system
5447 for encoding before it is sent.
5448
5449 This function can evaluate Lisp code and can garbage collect. */
5450
5451 static void
5452 send_process (volatile Lisp_Object proc, const char *volatile buf,
5453 volatile ptrdiff_t len, volatile Lisp_Object object)
5454 {
5455 /* Use volatile to protect variables from being clobbered by longjmp. */
5456 struct Lisp_Process *p = XPROCESS (proc);
5457 ssize_t rv;
5458 struct coding_system *coding;
5459 void (*volatile old_sigpipe) (int);
5460
5461 if (p->raw_status_new)
5462 update_status (p);
5463 if (! EQ (p->status, Qrun))
5464 error ("Process %s not running", SDATA (p->name));
5465 if (p->outfd < 0)
5466 error ("Output file descriptor of %s is closed", SDATA (p->name));
5467
5468 coding = proc_encode_coding_system[p->outfd];
5469 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5470
5471 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5472 || (BUFFERP (object)
5473 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5474 || EQ (object, Qt))
5475 {
5476 p->encode_coding_system
5477 = complement_process_encoding_system (p->encode_coding_system);
5478 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5479 {
5480 /* The coding system for encoding was changed to raw-text
5481 because we sent a unibyte text previously. Now we are
5482 sending a multibyte text, thus we must encode it by the
5483 original coding system specified for the current process.
5484
5485 Another reason we come here is that the coding system
5486 was just complemented and a new one was returned by
5487 complement_process_encoding_system. */
5488 setup_coding_system (p->encode_coding_system, coding);
5489 Vlast_coding_system_used = p->encode_coding_system;
5490 }
5491 coding->src_multibyte = 1;
5492 }
5493 else
5494 {
5495 coding->src_multibyte = 0;
5496 /* For sending a unibyte text, character code conversion should
5497 not take place but EOL conversion should. So, setup raw-text
5498 or one of the subsidiary if we have not yet done it. */
5499 if (CODING_REQUIRE_ENCODING (coding))
5500 {
5501 if (CODING_REQUIRE_FLUSHING (coding))
5502 {
5503 /* But, before changing the coding, we must flush out data. */
5504 coding->mode |= CODING_MODE_LAST_BLOCK;
5505 send_process (proc, "", 0, Qt);
5506 coding->mode &= CODING_MODE_LAST_BLOCK;
5507 }
5508 setup_coding_system (raw_text_coding_system
5509 (Vlast_coding_system_used),
5510 coding);
5511 coding->src_multibyte = 0;
5512 }
5513 }
5514 coding->dst_multibyte = 0;
5515
5516 if (CODING_REQUIRE_ENCODING (coding))
5517 {
5518 coding->dst_object = Qt;
5519 if (BUFFERP (object))
5520 {
5521 ptrdiff_t from_byte, from, to;
5522 ptrdiff_t save_pt, save_pt_byte;
5523 struct buffer *cur = current_buffer;
5524
5525 set_buffer_internal (XBUFFER (object));
5526 save_pt = PT, save_pt_byte = PT_BYTE;
5527
5528 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5529 from = BYTE_TO_CHAR (from_byte);
5530 to = BYTE_TO_CHAR (from_byte + len);
5531 TEMP_SET_PT_BOTH (from, from_byte);
5532 encode_coding_object (coding, object, from, from_byte,
5533 to, from_byte + len, Qt);
5534 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5535 set_buffer_internal (cur);
5536 }
5537 else if (STRINGP (object))
5538 {
5539 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5540 SBYTES (object), Qt);
5541 }
5542 else
5543 {
5544 coding->dst_object = make_unibyte_string (buf, len);
5545 coding->produced = len;
5546 }
5547
5548 len = coding->produced;
5549 object = coding->dst_object;
5550 buf = SSDATA (object);
5551 }
5552
5553 if (pty_max_bytes == 0)
5554 {
5555 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5556 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5557 if (pty_max_bytes < 0)
5558 pty_max_bytes = 250;
5559 #else
5560 pty_max_bytes = 250;
5561 #endif
5562 /* Deduct one, to leave space for the eof. */
5563 pty_max_bytes--;
5564 }
5565
5566 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5567 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5568 when returning with longjmp despite being declared volatile. */
5569 if (!setjmp (send_process_frame))
5570 {
5571 p = XPROCESS (proc); /* Repair any setjmp clobbering. */
5572 process_sent_to = proc;
5573
5574 /* If there is already data in the write_queue, put the new data
5575 in the back of queue. Otherwise, ignore it. */
5576 if (!NILP (p->write_queue))
5577 write_queue_push (p, object, buf, len, 0);
5578
5579 do /* while !NILP (p->write_queue) */
5580 {
5581 ptrdiff_t cur_len = -1;
5582 const char *cur_buf;
5583 Lisp_Object cur_object;
5584
5585 /* If write_queue is empty, ignore it. */
5586 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5587 {
5588 cur_len = len;
5589 cur_buf = buf;
5590 cur_object = object;
5591 }
5592
5593 while (cur_len > 0)
5594 {
5595 /* Send this batch, using one or more write calls. */
5596 ptrdiff_t written = 0;
5597 int outfd = p->outfd;
5598 old_sigpipe = (void (*) (int)) signal (SIGPIPE, send_process_trap);
5599 #ifdef DATAGRAM_SOCKETS
5600 if (DATAGRAM_CHAN_P (outfd))
5601 {
5602 rv = sendto (outfd, cur_buf, cur_len,
5603 0, datagram_address[outfd].sa,
5604 datagram_address[outfd].len);
5605 if (0 <= rv)
5606 written = rv;
5607 else if (errno == EMSGSIZE)
5608 {
5609 signal (SIGPIPE, old_sigpipe);
5610 report_file_error ("sending datagram",
5611 Fcons (proc, Qnil));
5612 }
5613 }
5614 else
5615 #endif
5616 {
5617 #ifdef HAVE_GNUTLS
5618 if (p->gnutls_p)
5619 written = emacs_gnutls_write (p, cur_buf, cur_len);
5620 else
5621 #endif
5622 written = emacs_write (outfd, cur_buf, cur_len);
5623 rv = (written ? 0 : -1);
5624 #ifdef ADAPTIVE_READ_BUFFERING
5625 if (p->read_output_delay > 0
5626 && p->adaptive_read_buffering == 1)
5627 {
5628 p->read_output_delay = 0;
5629 process_output_delay_count--;
5630 p->read_output_skip = 0;
5631 }
5632 #endif
5633 }
5634 signal (SIGPIPE, old_sigpipe);
5635
5636 if (rv < 0)
5637 {
5638 if (0
5639 #ifdef EWOULDBLOCK
5640 || errno == EWOULDBLOCK
5641 #endif
5642 #ifdef EAGAIN
5643 || errno == EAGAIN
5644 #endif
5645 )
5646 /* Buffer is full. Wait, accepting input;
5647 that may allow the program
5648 to finish doing output and read more. */
5649 {
5650 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5651 /* A gross hack to work around a bug in FreeBSD.
5652 In the following sequence, read(2) returns
5653 bogus data:
5654
5655 write(2) 1022 bytes
5656 write(2) 954 bytes, get EAGAIN
5657 read(2) 1024 bytes in process_read_output
5658 read(2) 11 bytes in process_read_output
5659
5660 That is, read(2) returns more bytes than have
5661 ever been written successfully. The 1033 bytes
5662 read are the 1022 bytes written successfully
5663 after processing (for example with CRs added if
5664 the terminal is set up that way which it is
5665 here). The same bytes will be seen again in a
5666 later read(2), without the CRs. */
5667
5668 if (errno == EAGAIN)
5669 {
5670 int flags = FWRITE;
5671 ioctl (p->outfd, TIOCFLUSH, &flags);
5672 }
5673 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5674
5675 /* Put what we should have written in wait_queue. */
5676 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5677 wait_reading_process_output (0, 20 * 1000 * 1000,
5678 0, 0, Qnil, NULL, 0);
5679 /* Reread queue, to see what is left. */
5680 break;
5681 }
5682 else
5683 /* This is a real error. */
5684 report_file_error ("writing to process", Fcons (proc, Qnil));
5685 }
5686 cur_buf += written;
5687 cur_len -= written;
5688 }
5689 }
5690 while (!NILP (p->write_queue));
5691 }
5692 else
5693 {
5694 signal (SIGPIPE, old_sigpipe);
5695 proc = process_sent_to;
5696 p = XPROCESS (proc);
5697 p->raw_status_new = 0;
5698 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5699 p->tick = ++process_tick;
5700 deactivate_process (proc);
5701 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5702 }
5703 }
5704
5705 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5706 3, 3, 0,
5707 doc: /* Send current contents of region as input to PROCESS.
5708 PROCESS may be a process, a buffer, the name of a process or buffer, or
5709 nil, indicating the current buffer's process.
5710 Called from program, takes three arguments, PROCESS, START and END.
5711 If the region is more than 500 characters long,
5712 it is sent in several bunches. This may happen even for shorter regions.
5713 Output from processes can arrive in between bunches. */)
5714 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5715 {
5716 Lisp_Object proc;
5717 ptrdiff_t start1, end1;
5718
5719 proc = get_process (process);
5720 validate_region (&start, &end);
5721
5722 if (XINT (start) < GPT && XINT (end) > GPT)
5723 move_gap (XINT (start));
5724
5725 start1 = CHAR_TO_BYTE (XINT (start));
5726 end1 = CHAR_TO_BYTE (XINT (end));
5727 send_process (proc, (char *) BYTE_POS_ADDR (start1), end1 - start1,
5728 Fcurrent_buffer ());
5729
5730 return Qnil;
5731 }
5732
5733 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5734 2, 2, 0,
5735 doc: /* Send PROCESS the contents of STRING as input.
5736 PROCESS may be a process, a buffer, the name of a process or buffer, or
5737 nil, indicating the current buffer's process.
5738 If STRING is more than 500 characters long,
5739 it is sent in several bunches. This may happen even for shorter strings.
5740 Output from processes can arrive in between bunches. */)
5741 (Lisp_Object process, Lisp_Object string)
5742 {
5743 Lisp_Object proc;
5744 CHECK_STRING (string);
5745 proc = get_process (process);
5746 send_process (proc, SSDATA (string),
5747 SBYTES (string), string);
5748 return Qnil;
5749 }
5750 \f
5751 /* Return the foreground process group for the tty/pty that
5752 the process P uses. */
5753 static pid_t
5754 emacs_get_tty_pgrp (struct Lisp_Process *p)
5755 {
5756 pid_t gid = -1;
5757
5758 #ifdef TIOCGPGRP
5759 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5760 {
5761 int fd;
5762 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5763 master side. Try the slave side. */
5764 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5765
5766 if (fd != -1)
5767 {
5768 ioctl (fd, TIOCGPGRP, &gid);
5769 emacs_close (fd);
5770 }
5771 }
5772 #endif /* defined (TIOCGPGRP ) */
5773
5774 return gid;
5775 }
5776
5777 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5778 Sprocess_running_child_p, 0, 1, 0,
5779 doc: /* Return t if PROCESS has given the terminal to a child.
5780 If the operating system does not make it possible to find out,
5781 return t unconditionally. */)
5782 (Lisp_Object process)
5783 {
5784 /* Initialize in case ioctl doesn't exist or gives an error,
5785 in a way that will cause returning t. */
5786 pid_t gid;
5787 Lisp_Object proc;
5788 struct Lisp_Process *p;
5789
5790 proc = get_process (process);
5791 p = XPROCESS (proc);
5792
5793 if (!EQ (p->type, Qreal))
5794 error ("Process %s is not a subprocess",
5795 SDATA (p->name));
5796 if (p->infd < 0)
5797 error ("Process %s is not active",
5798 SDATA (p->name));
5799
5800 gid = emacs_get_tty_pgrp (p);
5801
5802 if (gid == p->pid)
5803 return Qnil;
5804 return Qt;
5805 }
5806 \f
5807 /* send a signal number SIGNO to PROCESS.
5808 If CURRENT_GROUP is t, that means send to the process group
5809 that currently owns the terminal being used to communicate with PROCESS.
5810 This is used for various commands in shell mode.
5811 If CURRENT_GROUP is lambda, that means send to the process group
5812 that currently owns the terminal, but only if it is NOT the shell itself.
5813
5814 If NOMSG is zero, insert signal-announcements into process's buffers
5815 right away.
5816
5817 If we can, we try to signal PROCESS by sending control characters
5818 down the pty. This allows us to signal inferiors who have changed
5819 their uid, for which killpg would return an EPERM error. */
5820
5821 static void
5822 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5823 int nomsg)
5824 {
5825 Lisp_Object proc;
5826 register struct Lisp_Process *p;
5827 pid_t gid;
5828 int no_pgrp = 0;
5829
5830 proc = get_process (process);
5831 p = XPROCESS (proc);
5832
5833 if (!EQ (p->type, Qreal))
5834 error ("Process %s is not a subprocess",
5835 SDATA (p->name));
5836 if (p->infd < 0)
5837 error ("Process %s is not active",
5838 SDATA (p->name));
5839
5840 if (!p->pty_flag)
5841 current_group = Qnil;
5842
5843 /* If we are using pgrps, get a pgrp number and make it negative. */
5844 if (NILP (current_group))
5845 /* Send the signal to the shell's process group. */
5846 gid = p->pid;
5847 else
5848 {
5849 #ifdef SIGNALS_VIA_CHARACTERS
5850 /* If possible, send signals to the entire pgrp
5851 by sending an input character to it. */
5852
5853 struct termios t;
5854 cc_t *sig_char = NULL;
5855
5856 tcgetattr (p->infd, &t);
5857
5858 switch (signo)
5859 {
5860 case SIGINT:
5861 sig_char = &t.c_cc[VINTR];
5862 break;
5863
5864 case SIGQUIT:
5865 sig_char = &t.c_cc[VQUIT];
5866 break;
5867
5868 case SIGTSTP:
5869 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5870 sig_char = &t.c_cc[VSWTCH];
5871 #else
5872 sig_char = &t.c_cc[VSUSP];
5873 #endif
5874 break;
5875 }
5876
5877 if (sig_char && *sig_char != CDISABLE)
5878 {
5879 send_process (proc, (char *) sig_char, 1, Qnil);
5880 return;
5881 }
5882 /* If we can't send the signal with a character,
5883 fall through and send it another way. */
5884
5885 /* The code above may fall through if it can't
5886 handle the signal. */
5887 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5888
5889 #ifdef TIOCGPGRP
5890 /* Get the current pgrp using the tty itself, if we have that.
5891 Otherwise, use the pty to get the pgrp.
5892 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5893 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5894 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5895 His patch indicates that if TIOCGPGRP returns an error, then
5896 we should just assume that p->pid is also the process group id. */
5897
5898 gid = emacs_get_tty_pgrp (p);
5899
5900 if (gid == -1)
5901 /* If we can't get the information, assume
5902 the shell owns the tty. */
5903 gid = p->pid;
5904
5905 /* It is not clear whether anything really can set GID to -1.
5906 Perhaps on some system one of those ioctls can or could do so.
5907 Or perhaps this is vestigial. */
5908 if (gid == -1)
5909 no_pgrp = 1;
5910 #else /* ! defined (TIOCGPGRP ) */
5911 /* Can't select pgrps on this system, so we know that
5912 the child itself heads the pgrp. */
5913 gid = p->pid;
5914 #endif /* ! defined (TIOCGPGRP ) */
5915
5916 /* If current_group is lambda, and the shell owns the terminal,
5917 don't send any signal. */
5918 if (EQ (current_group, Qlambda) && gid == p->pid)
5919 return;
5920 }
5921
5922 switch (signo)
5923 {
5924 #ifdef SIGCONT
5925 case SIGCONT:
5926 p->raw_status_new = 0;
5927 p->status = Qrun;
5928 p->tick = ++process_tick;
5929 if (!nomsg)
5930 {
5931 status_notify (NULL);
5932 redisplay_preserve_echo_area (13);
5933 }
5934 break;
5935 #endif /* ! defined (SIGCONT) */
5936 case SIGINT:
5937 case SIGQUIT:
5938 case SIGKILL:
5939 flush_pending_output (p->infd);
5940 break;
5941 }
5942
5943 /* If we don't have process groups, send the signal to the immediate
5944 subprocess. That isn't really right, but it's better than any
5945 obvious alternative. */
5946 if (no_pgrp)
5947 {
5948 kill (p->pid, signo);
5949 return;
5950 }
5951
5952 /* gid may be a pid, or minus a pgrp's number */
5953 #ifdef TIOCSIGSEND
5954 if (!NILP (current_group))
5955 {
5956 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5957 EMACS_KILLPG (gid, signo);
5958 }
5959 else
5960 {
5961 gid = - p->pid;
5962 kill (gid, signo);
5963 }
5964 #else /* ! defined (TIOCSIGSEND) */
5965 EMACS_KILLPG (gid, signo);
5966 #endif /* ! defined (TIOCSIGSEND) */
5967 }
5968
5969 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5970 doc: /* Interrupt process PROCESS.
5971 PROCESS may be a process, a buffer, or the name of a process or buffer.
5972 No arg or nil means current buffer's process.
5973 Second arg CURRENT-GROUP non-nil means send signal to
5974 the current process-group of the process's controlling terminal
5975 rather than to the process's own process group.
5976 If the process is a shell, this means interrupt current subjob
5977 rather than the shell.
5978
5979 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5980 don't send the signal. */)
5981 (Lisp_Object process, Lisp_Object current_group)
5982 {
5983 process_send_signal (process, SIGINT, current_group, 0);
5984 return process;
5985 }
5986
5987 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5988 doc: /* Kill process PROCESS. May be process or name of one.
5989 See function `interrupt-process' for more details on usage. */)
5990 (Lisp_Object process, Lisp_Object current_group)
5991 {
5992 process_send_signal (process, SIGKILL, current_group, 0);
5993 return process;
5994 }
5995
5996 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5997 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5998 See function `interrupt-process' for more details on usage. */)
5999 (Lisp_Object process, Lisp_Object current_group)
6000 {
6001 process_send_signal (process, SIGQUIT, current_group, 0);
6002 return process;
6003 }
6004
6005 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6006 doc: /* Stop process PROCESS. May be process or name of one.
6007 See function `interrupt-process' for more details on usage.
6008 If PROCESS is a network or serial process, inhibit handling of incoming
6009 traffic. */)
6010 (Lisp_Object process, Lisp_Object current_group)
6011 {
6012 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6013 {
6014 struct Lisp_Process *p;
6015
6016 p = XPROCESS (process);
6017 if (NILP (p->command)
6018 && p->infd >= 0)
6019 {
6020 FD_CLR (p->infd, &input_wait_mask);
6021 FD_CLR (p->infd, &non_keyboard_wait_mask);
6022 }
6023 p->command = Qt;
6024 return process;
6025 }
6026 #ifndef SIGTSTP
6027 error ("No SIGTSTP support");
6028 #else
6029 process_send_signal (process, SIGTSTP, current_group, 0);
6030 #endif
6031 return process;
6032 }
6033
6034 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6035 doc: /* Continue process PROCESS. May be process or name of one.
6036 See function `interrupt-process' for more details on usage.
6037 If PROCESS is a network or serial process, resume handling of incoming
6038 traffic. */)
6039 (Lisp_Object process, Lisp_Object current_group)
6040 {
6041 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6042 {
6043 struct Lisp_Process *p;
6044
6045 p = XPROCESS (process);
6046 if (EQ (p->command, Qt)
6047 && p->infd >= 0
6048 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6049 {
6050 FD_SET (p->infd, &input_wait_mask);
6051 FD_SET (p->infd, &non_keyboard_wait_mask);
6052 #ifdef WINDOWSNT
6053 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6054 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6055 #else /* not WINDOWSNT */
6056 tcflush (p->infd, TCIFLUSH);
6057 #endif /* not WINDOWSNT */
6058 }
6059 p->command = Qnil;
6060 return process;
6061 }
6062 #ifdef SIGCONT
6063 process_send_signal (process, SIGCONT, current_group, 0);
6064 #else
6065 error ("No SIGCONT support");
6066 #endif
6067 return process;
6068 }
6069
6070 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6071 2, 2, "sProcess (name or number): \nnSignal code: ",
6072 doc: /* Send PROCESS the signal with code SIGCODE.
6073 PROCESS may also be a number specifying the process id of the
6074 process to signal; in this case, the process need not be a child of
6075 this Emacs.
6076 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6077 (Lisp_Object process, Lisp_Object sigcode)
6078 {
6079 pid_t pid;
6080
6081 if (STRINGP (process))
6082 {
6083 Lisp_Object tem = Fget_process (process);
6084 if (NILP (tem))
6085 {
6086 Lisp_Object process_number =
6087 string_to_number (SSDATA (process), 10, 1);
6088 if (INTEGERP (process_number) || FLOATP (process_number))
6089 tem = process_number;
6090 }
6091 process = tem;
6092 }
6093 else if (!NUMBERP (process))
6094 process = get_process (process);
6095
6096 if (NILP (process))
6097 return process;
6098
6099 if (NUMBERP (process))
6100 CONS_TO_INTEGER (process, pid_t, pid);
6101 else
6102 {
6103 CHECK_PROCESS (process);
6104 pid = XPROCESS (process)->pid;
6105 if (pid <= 0)
6106 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6107 }
6108
6109 #define parse_signal(NAME, VALUE) \
6110 else if (!xstrcasecmp (name, NAME)) \
6111 XSETINT (sigcode, VALUE)
6112
6113 if (INTEGERP (sigcode))
6114 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
6115 else
6116 {
6117 char *name;
6118
6119 CHECK_SYMBOL (sigcode);
6120 name = SSDATA (SYMBOL_NAME (sigcode));
6121
6122 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6123 name += 3;
6124
6125 if (0)
6126 ;
6127 #ifdef SIGUSR1
6128 parse_signal ("usr1", SIGUSR1);
6129 #endif
6130 #ifdef SIGUSR2
6131 parse_signal ("usr2", SIGUSR2);
6132 #endif
6133 #ifdef SIGTERM
6134 parse_signal ("term", SIGTERM);
6135 #endif
6136 #ifdef SIGHUP
6137 parse_signal ("hup", SIGHUP);
6138 #endif
6139 #ifdef SIGINT
6140 parse_signal ("int", SIGINT);
6141 #endif
6142 #ifdef SIGQUIT
6143 parse_signal ("quit", SIGQUIT);
6144 #endif
6145 #ifdef SIGILL
6146 parse_signal ("ill", SIGILL);
6147 #endif
6148 #ifdef SIGABRT
6149 parse_signal ("abrt", SIGABRT);
6150 #endif
6151 #ifdef SIGEMT
6152 parse_signal ("emt", SIGEMT);
6153 #endif
6154 #ifdef SIGKILL
6155 parse_signal ("kill", SIGKILL);
6156 #endif
6157 #ifdef SIGFPE
6158 parse_signal ("fpe", SIGFPE);
6159 #endif
6160 #ifdef SIGBUS
6161 parse_signal ("bus", SIGBUS);
6162 #endif
6163 #ifdef SIGSEGV
6164 parse_signal ("segv", SIGSEGV);
6165 #endif
6166 #ifdef SIGSYS
6167 parse_signal ("sys", SIGSYS);
6168 #endif
6169 #ifdef SIGPIPE
6170 parse_signal ("pipe", SIGPIPE);
6171 #endif
6172 #ifdef SIGALRM
6173 parse_signal ("alrm", SIGALRM);
6174 #endif
6175 #ifdef SIGURG
6176 parse_signal ("urg", SIGURG);
6177 #endif
6178 #ifdef SIGSTOP
6179 parse_signal ("stop", SIGSTOP);
6180 #endif
6181 #ifdef SIGTSTP
6182 parse_signal ("tstp", SIGTSTP);
6183 #endif
6184 #ifdef SIGCONT
6185 parse_signal ("cont", SIGCONT);
6186 #endif
6187 #ifdef SIGCHLD
6188 parse_signal ("chld", SIGCHLD);
6189 #endif
6190 #ifdef SIGTTIN
6191 parse_signal ("ttin", SIGTTIN);
6192 #endif
6193 #ifdef SIGTTOU
6194 parse_signal ("ttou", SIGTTOU);
6195 #endif
6196 #ifdef SIGIO
6197 parse_signal ("io", SIGIO);
6198 #endif
6199 #ifdef SIGXCPU
6200 parse_signal ("xcpu", SIGXCPU);
6201 #endif
6202 #ifdef SIGXFSZ
6203 parse_signal ("xfsz", SIGXFSZ);
6204 #endif
6205 #ifdef SIGVTALRM
6206 parse_signal ("vtalrm", SIGVTALRM);
6207 #endif
6208 #ifdef SIGPROF
6209 parse_signal ("prof", SIGPROF);
6210 #endif
6211 #ifdef SIGWINCH
6212 parse_signal ("winch", SIGWINCH);
6213 #endif
6214 #ifdef SIGINFO
6215 parse_signal ("info", SIGINFO);
6216 #endif
6217 else
6218 error ("Undefined signal name %s", name);
6219 }
6220
6221 #undef parse_signal
6222
6223 return make_number (kill (pid, XINT (sigcode)));
6224 }
6225
6226 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6227 doc: /* Make PROCESS see end-of-file in its input.
6228 EOF comes after any text already sent to it.
6229 PROCESS may be a process, a buffer, the name of a process or buffer, or
6230 nil, indicating the current buffer's process.
6231 If PROCESS is a network connection, or is a process communicating
6232 through a pipe (as opposed to a pty), then you cannot send any more
6233 text to PROCESS after you call this function.
6234 If PROCESS is a serial process, wait until all output written to the
6235 process has been transmitted to the serial port. */)
6236 (Lisp_Object process)
6237 {
6238 Lisp_Object proc;
6239 struct coding_system *coding;
6240
6241 if (DATAGRAM_CONN_P (process))
6242 return process;
6243
6244 proc = get_process (process);
6245 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6246
6247 /* Make sure the process is really alive. */
6248 if (XPROCESS (proc)->raw_status_new)
6249 update_status (XPROCESS (proc));
6250 if (! EQ (XPROCESS (proc)->status, Qrun))
6251 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6252
6253 if (CODING_REQUIRE_FLUSHING (coding))
6254 {
6255 coding->mode |= CODING_MODE_LAST_BLOCK;
6256 send_process (proc, "", 0, Qnil);
6257 }
6258
6259 if (XPROCESS (proc)->pty_flag)
6260 send_process (proc, "\004", 1, Qnil);
6261 else if (EQ (XPROCESS (proc)->type, Qserial))
6262 {
6263 #ifndef WINDOWSNT
6264 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6265 error ("tcdrain() failed: %s", emacs_strerror (errno));
6266 #endif /* not WINDOWSNT */
6267 /* Do nothing on Windows because writes are blocking. */
6268 }
6269 else
6270 {
6271 int old_outfd, new_outfd;
6272
6273 #ifdef HAVE_SHUTDOWN
6274 /* If this is a network connection, or socketpair is used
6275 for communication with the subprocess, call shutdown to cause EOF.
6276 (In some old system, shutdown to socketpair doesn't work.
6277 Then we just can't win.) */
6278 if (EQ (XPROCESS (proc)->type, Qnetwork)
6279 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6280 shutdown (XPROCESS (proc)->outfd, 1);
6281 /* In case of socketpair, outfd == infd, so don't close it. */
6282 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6283 emacs_close (XPROCESS (proc)->outfd);
6284 #else /* not HAVE_SHUTDOWN */
6285 emacs_close (XPROCESS (proc)->outfd);
6286 #endif /* not HAVE_SHUTDOWN */
6287 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6288 if (new_outfd < 0)
6289 abort ();
6290 old_outfd = XPROCESS (proc)->outfd;
6291
6292 if (!proc_encode_coding_system[new_outfd])
6293 proc_encode_coding_system[new_outfd]
6294 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6295 memcpy (proc_encode_coding_system[new_outfd],
6296 proc_encode_coding_system[old_outfd],
6297 sizeof (struct coding_system));
6298 memset (proc_encode_coding_system[old_outfd], 0,
6299 sizeof (struct coding_system));
6300
6301 XPROCESS (proc)->outfd = new_outfd;
6302 }
6303 return process;
6304 }
6305 \f
6306 /* On receipt of a signal that a child status has changed, loop asking
6307 about children with changed statuses until the system says there
6308 are no more.
6309
6310 All we do is change the status; we do not run sentinels or print
6311 notifications. That is saved for the next time keyboard input is
6312 done, in order to avoid timing errors.
6313
6314 ** WARNING: this can be called during garbage collection.
6315 Therefore, it must not be fooled by the presence of mark bits in
6316 Lisp objects.
6317
6318 ** USG WARNING: Although it is not obvious from the documentation
6319 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6320 signal() before executing at least one wait(), otherwise the
6321 handler will be called again, resulting in an infinite loop. The
6322 relevant portion of the documentation reads "SIGCLD signals will be
6323 queued and the signal-catching function will be continually
6324 reentered until the queue is empty". Invoking signal() causes the
6325 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6326 Inc.
6327
6328 ** Malloc WARNING: This should never call malloc either directly or
6329 indirectly; if it does, that is a bug */
6330
6331 #ifdef SIGCHLD
6332 static void
6333 sigchld_handler (int signo)
6334 {
6335 int old_errno = errno;
6336 Lisp_Object proc;
6337 struct Lisp_Process *p;
6338
6339 SIGNAL_THREAD_CHECK (signo);
6340
6341 while (1)
6342 {
6343 pid_t pid;
6344 int w;
6345 Lisp_Object tail;
6346
6347 #ifdef WNOHANG
6348 #ifndef WUNTRACED
6349 #define WUNTRACED 0
6350 #endif /* no WUNTRACED */
6351 /* Keep trying to get a status until we get a definitive result. */
6352 do
6353 {
6354 errno = 0;
6355 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6356 }
6357 while (pid < 0 && errno == EINTR);
6358
6359 if (pid <= 0)
6360 {
6361 /* PID == 0 means no processes found, PID == -1 means a real
6362 failure. We have done all our job, so return. */
6363
6364 errno = old_errno;
6365 return;
6366 }
6367 #else
6368 pid = wait (&w);
6369 #endif /* no WNOHANG */
6370
6371 /* Find the process that signaled us, and record its status. */
6372
6373 /* The process can have been deleted by Fdelete_process. */
6374 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6375 {
6376 Lisp_Object xpid = XCAR (tail);
6377 if ((INTEGERP (xpid) && pid == XINT (xpid))
6378 || (FLOATP (xpid) && pid == XFLOAT_DATA (xpid)))
6379 {
6380 XSETCAR (tail, Qnil);
6381 goto sigchld_end_of_loop;
6382 }
6383 }
6384
6385 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6386 p = 0;
6387 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6388 {
6389 proc = XCDR (XCAR (tail));
6390 p = XPROCESS (proc);
6391 if (EQ (p->type, Qreal) && p->pid == pid)
6392 break;
6393 p = 0;
6394 }
6395
6396 /* Look for an asynchronous process whose pid hasn't been filled
6397 in yet. */
6398 if (p == 0)
6399 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6400 {
6401 proc = XCDR (XCAR (tail));
6402 p = XPROCESS (proc);
6403 if (p->pid == -1)
6404 break;
6405 p = 0;
6406 }
6407
6408 /* Change the status of the process that was found. */
6409 if (p != 0)
6410 {
6411 int clear_desc_flag = 0;
6412
6413 p->tick = ++process_tick;
6414 p->raw_status = w;
6415 p->raw_status_new = 1;
6416
6417 /* If process has terminated, stop waiting for its output. */
6418 if ((WIFSIGNALED (w) || WIFEXITED (w))
6419 && p->infd >= 0)
6420 clear_desc_flag = 1;
6421
6422 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6423 if (clear_desc_flag)
6424 {
6425 FD_CLR (p->infd, &input_wait_mask);
6426 FD_CLR (p->infd, &non_keyboard_wait_mask);
6427 }
6428
6429 /* Tell wait_reading_process_output that it needs to wake up and
6430 look around. */
6431 if (input_available_clear_time)
6432 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6433 }
6434
6435 /* There was no asynchronous process found for that pid: we have
6436 a synchronous process. */
6437 else
6438 {
6439 synch_process_alive = 0;
6440
6441 /* Report the status of the synchronous process. */
6442 if (WIFEXITED (w))
6443 synch_process_retcode = WRETCODE (w);
6444 else if (WIFSIGNALED (w))
6445 synch_process_termsig = WTERMSIG (w);
6446
6447 /* Tell wait_reading_process_output that it needs to wake up and
6448 look around. */
6449 if (input_available_clear_time)
6450 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6451 }
6452
6453 sigchld_end_of_loop:
6454 ;
6455
6456 /* On some systems, we must return right away.
6457 If any more processes want to signal us, we will
6458 get another signal.
6459 Otherwise (on systems that have WNOHANG), loop around
6460 to use up all the processes that have something to tell us. */
6461 #if (defined WINDOWSNT \
6462 || (defined USG && !defined GNU_LINUX \
6463 && !(defined HPUX && defined WNOHANG)))
6464 errno = old_errno;
6465 return;
6466 #endif /* USG, but not HPUX with WNOHANG */
6467 }
6468 }
6469 #endif /* SIGCHLD */
6470 \f
6471
6472 static Lisp_Object
6473 exec_sentinel_unwind (Lisp_Object data)
6474 {
6475 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6476 return Qnil;
6477 }
6478
6479 static Lisp_Object
6480 exec_sentinel_error_handler (Lisp_Object error_val)
6481 {
6482 cmd_error_internal (error_val, "error in process sentinel: ");
6483 Vinhibit_quit = Qt;
6484 update_echo_area ();
6485 Fsleep_for (make_number (2), Qnil);
6486 return Qt;
6487 }
6488
6489 static void
6490 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6491 {
6492 Lisp_Object sentinel, odeactivate;
6493 register struct Lisp_Process *p = XPROCESS (proc);
6494 ptrdiff_t count = SPECPDL_INDEX ();
6495 int outer_running_asynch_code = running_asynch_code;
6496 int waiting = waiting_for_user_input_p;
6497
6498 if (inhibit_sentinels)
6499 return;
6500
6501 /* No need to gcpro these, because all we do with them later
6502 is test them for EQness, and none of them should be a string. */
6503 odeactivate = Vdeactivate_mark;
6504 #if 0
6505 Lisp_Object obuffer, okeymap;
6506 XSETBUFFER (obuffer, current_buffer);
6507 okeymap = BVAR (current_buffer, keymap);
6508 #endif
6509
6510 /* There's no good reason to let sentinels change the current
6511 buffer, and many callers of accept-process-output, sit-for, and
6512 friends don't expect current-buffer to be changed from under them. */
6513 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
6514
6515 sentinel = p->sentinel;
6516 if (NILP (sentinel))
6517 return;
6518
6519 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6520 assure that it gets restored no matter how the sentinel exits. */
6521 p->sentinel = Qnil;
6522 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6523 /* Inhibit quit so that random quits don't screw up a running filter. */
6524 specbind (Qinhibit_quit, Qt);
6525 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6526
6527 /* In case we get recursively called,
6528 and we already saved the match data nonrecursively,
6529 save the same match data in safely recursive fashion. */
6530 if (outer_running_asynch_code)
6531 {
6532 Lisp_Object tem;
6533 tem = Fmatch_data (Qnil, Qnil, Qnil);
6534 restore_search_regs ();
6535 record_unwind_save_match_data ();
6536 Fset_match_data (tem, Qt);
6537 }
6538
6539 /* For speed, if a search happens within this code,
6540 save the match data in a special nonrecursive fashion. */
6541 running_asynch_code = 1;
6542
6543 internal_condition_case_1 (read_process_output_call,
6544 Fcons (sentinel,
6545 Fcons (proc, Fcons (reason, Qnil))),
6546 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6547 exec_sentinel_error_handler);
6548
6549 /* If we saved the match data nonrecursively, restore it now. */
6550 restore_search_regs ();
6551 running_asynch_code = outer_running_asynch_code;
6552
6553 Vdeactivate_mark = odeactivate;
6554
6555 /* Restore waiting_for_user_input_p as it was
6556 when we were called, in case the filter clobbered it. */
6557 waiting_for_user_input_p = waiting;
6558
6559 #if 0
6560 if (! EQ (Fcurrent_buffer (), obuffer)
6561 || ! EQ (current_buffer->keymap, okeymap))
6562 #endif
6563 /* But do it only if the caller is actually going to read events.
6564 Otherwise there's no need to make him wake up, and it could
6565 cause trouble (for example it would make sit_for return). */
6566 if (waiting_for_user_input_p == -1)
6567 record_asynch_buffer_change ();
6568
6569 unbind_to (count, Qnil);
6570 }
6571
6572 /* Report all recent events of a change in process status
6573 (either run the sentinel or output a message).
6574 This is usually done while Emacs is waiting for keyboard input
6575 but can be done at other times. */
6576
6577 static void
6578 status_notify (struct Lisp_Process *deleting_process)
6579 {
6580 register Lisp_Object proc, buffer;
6581 Lisp_Object tail, msg;
6582 struct gcpro gcpro1, gcpro2;
6583
6584 tail = Qnil;
6585 msg = Qnil;
6586 /* We need to gcpro tail; if read_process_output calls a filter
6587 which deletes a process and removes the cons to which tail points
6588 from Vprocess_alist, and then causes a GC, tail is an unprotected
6589 reference. */
6590 GCPRO2 (tail, msg);
6591
6592 /* Set this now, so that if new processes are created by sentinels
6593 that we run, we get called again to handle their status changes. */
6594 update_tick = process_tick;
6595
6596 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6597 {
6598 Lisp_Object symbol;
6599 register struct Lisp_Process *p;
6600
6601 proc = Fcdr (XCAR (tail));
6602 p = XPROCESS (proc);
6603
6604 if (p->tick != p->update_tick)
6605 {
6606 p->update_tick = p->tick;
6607
6608 /* If process is still active, read any output that remains. */
6609 while (! EQ (p->filter, Qt)
6610 && ! EQ (p->status, Qconnect)
6611 && ! EQ (p->status, Qlisten)
6612 /* Network or serial process not stopped: */
6613 && ! EQ (p->command, Qt)
6614 && p->infd >= 0
6615 && p != deleting_process
6616 && read_process_output (proc, p->infd) > 0);
6617
6618 buffer = p->buffer;
6619
6620 /* Get the text to use for the message. */
6621 if (p->raw_status_new)
6622 update_status (p);
6623 msg = status_message (p);
6624
6625 /* If process is terminated, deactivate it or delete it. */
6626 symbol = p->status;
6627 if (CONSP (p->status))
6628 symbol = XCAR (p->status);
6629
6630 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6631 || EQ (symbol, Qclosed))
6632 {
6633 if (delete_exited_processes)
6634 remove_process (proc);
6635 else
6636 deactivate_process (proc);
6637 }
6638
6639 /* The actions above may have further incremented p->tick.
6640 So set p->update_tick again
6641 so that an error in the sentinel will not cause
6642 this code to be run again. */
6643 p->update_tick = p->tick;
6644 /* Now output the message suitably. */
6645 if (!NILP (p->sentinel))
6646 exec_sentinel (proc, msg);
6647 /* Don't bother with a message in the buffer
6648 when a process becomes runnable. */
6649 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6650 {
6651 Lisp_Object tem;
6652 struct buffer *old = current_buffer;
6653 ptrdiff_t opoint, opoint_byte;
6654 ptrdiff_t before, before_byte;
6655
6656 /* Avoid error if buffer is deleted
6657 (probably that's why the process is dead, too) */
6658 if (NILP (BVAR (XBUFFER (buffer), name)))
6659 continue;
6660 Fset_buffer (buffer);
6661
6662 opoint = PT;
6663 opoint_byte = PT_BYTE;
6664 /* Insert new output into buffer
6665 at the current end-of-output marker,
6666 thus preserving logical ordering of input and output. */
6667 if (XMARKER (p->mark)->buffer)
6668 Fgoto_char (p->mark);
6669 else
6670 SET_PT_BOTH (ZV, ZV_BYTE);
6671
6672 before = PT;
6673 before_byte = PT_BYTE;
6674
6675 tem = BVAR (current_buffer, read_only);
6676 BVAR (current_buffer, read_only) = Qnil;
6677 insert_string ("\nProcess ");
6678 Finsert (1, &p->name);
6679 insert_string (" ");
6680 Finsert (1, &msg);
6681 BVAR (current_buffer, read_only) = tem;
6682 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6683
6684 if (opoint >= before)
6685 SET_PT_BOTH (opoint + (PT - before),
6686 opoint_byte + (PT_BYTE - before_byte));
6687 else
6688 SET_PT_BOTH (opoint, opoint_byte);
6689
6690 set_buffer_internal (old);
6691 }
6692 }
6693 } /* end for */
6694
6695 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6696 UNGCPRO;
6697 }
6698
6699 \f
6700 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6701 Sset_process_coding_system, 1, 3, 0,
6702 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6703 DECODING will be used to decode subprocess output and ENCODING to
6704 encode subprocess input. */)
6705 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6706 {
6707 register struct Lisp_Process *p;
6708
6709 CHECK_PROCESS (process);
6710 p = XPROCESS (process);
6711 if (p->infd < 0)
6712 error ("Input file descriptor of %s closed", SDATA (p->name));
6713 if (p->outfd < 0)
6714 error ("Output file descriptor of %s closed", SDATA (p->name));
6715 Fcheck_coding_system (decoding);
6716 Fcheck_coding_system (encoding);
6717 encoding = coding_inherit_eol_type (encoding, Qnil);
6718 p->decode_coding_system = decoding;
6719 p->encode_coding_system = encoding;
6720 setup_process_coding_systems (process);
6721
6722 return Qnil;
6723 }
6724
6725 DEFUN ("process-coding-system",
6726 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6727 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6728 (register Lisp_Object process)
6729 {
6730 CHECK_PROCESS (process);
6731 return Fcons (XPROCESS (process)->decode_coding_system,
6732 XPROCESS (process)->encode_coding_system);
6733 }
6734
6735 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6736 Sset_process_filter_multibyte, 2, 2, 0,
6737 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6738 If FLAG is non-nil, the filter is given multibyte strings.
6739 If FLAG is nil, the filter is given unibyte strings. In this case,
6740 all character code conversion except for end-of-line conversion is
6741 suppressed. */)
6742 (Lisp_Object process, Lisp_Object flag)
6743 {
6744 register struct Lisp_Process *p;
6745
6746 CHECK_PROCESS (process);
6747 p = XPROCESS (process);
6748 if (NILP (flag))
6749 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
6750 setup_process_coding_systems (process);
6751
6752 return Qnil;
6753 }
6754
6755 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6756 Sprocess_filter_multibyte_p, 1, 1, 0,
6757 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6758 (Lisp_Object process)
6759 {
6760 register struct Lisp_Process *p;
6761 struct coding_system *coding;
6762
6763 CHECK_PROCESS (process);
6764 p = XPROCESS (process);
6765 coding = proc_decode_coding_system[p->infd];
6766 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6767 }
6768
6769
6770 \f
6771
6772 # ifdef HAVE_GPM
6773
6774 void
6775 add_gpm_wait_descriptor (int desc)
6776 {
6777 add_keyboard_wait_descriptor (desc);
6778 }
6779
6780 void
6781 delete_gpm_wait_descriptor (int desc)
6782 {
6783 delete_keyboard_wait_descriptor (desc);
6784 }
6785
6786 # endif
6787
6788 # ifdef SIGIO
6789
6790 /* Return nonzero if *MASK has a bit set
6791 that corresponds to one of the keyboard input descriptors. */
6792
6793 static int
6794 keyboard_bit_set (fd_set *mask)
6795 {
6796 int fd;
6797
6798 for (fd = 0; fd <= max_input_desc; fd++)
6799 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6800 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6801 return 1;
6802
6803 return 0;
6804 }
6805 # endif
6806
6807 #else /* not subprocesses */
6808
6809 /* Defined on msdos.c. */
6810 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6811 EMACS_TIME *);
6812
6813 /* Implementation of wait_reading_process_output, assuming that there
6814 are no subprocesses. Used only by the MS-DOS build.
6815
6816 Wait for timeout to elapse and/or keyboard input to be available.
6817
6818 TIME_LIMIT is:
6819 timeout in seconds
6820 If negative, gobble data immediately available but don't wait for any.
6821
6822 NSECS is:
6823 an additional duration to wait, measured in nanoseconds
6824 If TIME_LIMIT is zero, then:
6825 If NSECS == 0, there is no limit.
6826 If NSECS > 0, the timeout consists of NSECS only.
6827 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6828
6829 READ_KBD is a Lisp_Object:
6830 0 to ignore keyboard input, or
6831 1 to return when input is available, or
6832 -1 means caller will actually read the input, so don't throw to
6833 the quit handler.
6834
6835 see full version for other parameters. We know that wait_proc will
6836 always be NULL, since `subprocesses' isn't defined.
6837
6838 DO_DISPLAY != 0 means redisplay should be done to show subprocess
6839 output that arrives.
6840
6841 Return true if we received input from any process. */
6842
6843 int
6844 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6845 int do_display,
6846 Lisp_Object wait_for_cell,
6847 struct Lisp_Process *wait_proc, int just_wait_proc)
6848 {
6849 register int nfds;
6850 EMACS_TIME end_time, timeout;
6851 SELECT_TYPE waitchannels;
6852 int xerrno;
6853
6854 if (time_limit < 0)
6855 {
6856 time_limit = 0;
6857 nsecs = -1;
6858 }
6859 else if (TYPE_MAXIMUM (time_t) < time_limit)
6860 time_limit = TYPE_MAXIMUM (time_t);
6861
6862 /* What does time_limit really mean? */
6863 if (time_limit || nsecs) /* FIXME: what if negative? */
6864 {
6865 EMACS_GET_TIME (end_time);
6866 EMACS_SET_SECS_NSECS (timeout, time_limit, nsecs);
6867 EMACS_ADD_TIME (end_time, end_time, timeout);
6868 }
6869
6870 /* Turn off periodic alarms (in case they are in use)
6871 and then turn off any other atimers,
6872 because the select emulator uses alarms. */
6873 stop_polling ();
6874 turn_on_atimers (0);
6875
6876 while (1)
6877 {
6878 int timeout_reduced_for_timers = 0;
6879
6880 /* If calling from keyboard input, do not quit
6881 since we want to return C-g as an input character.
6882 Otherwise, do pending quit if requested. */
6883 if (read_kbd >= 0)
6884 QUIT;
6885
6886 /* Exit now if the cell we're waiting for became non-nil. */
6887 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6888 break;
6889
6890 /* Compute time from now till when time limit is up */
6891 /* Exit if already run out */
6892 if (nsecs < 0)
6893 {
6894 /* -1 specified for timeout means
6895 gobble output available now
6896 but don't wait at all. */
6897
6898 EMACS_SET_SECS_USECS (timeout, 0, 0);
6899 }
6900 else if (time_limit || nsecs)
6901 {
6902 EMACS_GET_TIME (timeout);
6903 if (EMACS_TIME_LE (end_time, timeout))
6904 break;
6905 EMACS_SUB_TIME (timeout, end_time, timeout);
6906 }
6907 else
6908 {
6909 EMACS_SET_SECS_USECS (timeout, 100000, 0);
6910 }
6911
6912 /* If our caller will not immediately handle keyboard events,
6913 run timer events directly.
6914 (Callers that will immediately read keyboard events
6915 call timer_delay on their own.) */
6916 if (NILP (wait_for_cell))
6917 {
6918 EMACS_TIME timer_delay;
6919
6920 do
6921 {
6922 int old_timers_run = timers_run;
6923 timer_delay = timer_check ();
6924 if (timers_run != old_timers_run && do_display)
6925 /* We must retry, since a timer may have requeued itself
6926 and that could alter the time delay. */
6927 redisplay_preserve_echo_area (14);
6928 else
6929 break;
6930 }
6931 while (!detect_input_pending ());
6932
6933 /* If there is unread keyboard input, also return. */
6934 if (read_kbd != 0
6935 && requeued_events_pending_p ())
6936 break;
6937
6938 if (EMACS_TIME_VALID_P (timer_delay) && 0 <= nsecs)
6939 {
6940 if (EMACS_TIME_LT (timer_delay, timeout))
6941 {
6942 timeout = timer_delay;
6943 timeout_reduced_for_timers = 1;
6944 }
6945 }
6946 }
6947
6948 /* Cause C-g and alarm signals to take immediate action,
6949 and cause input available signals to zero out timeout. */
6950 if (read_kbd < 0)
6951 set_waiting_for_input (&timeout);
6952
6953 /* Wait till there is something to do. */
6954
6955 if (! read_kbd && NILP (wait_for_cell))
6956 FD_ZERO (&waitchannels);
6957 else
6958 FD_SET (0, &waitchannels);
6959
6960 /* If a frame has been newly mapped and needs updating,
6961 reprocess its display stuff. */
6962 if (frame_garbaged && do_display)
6963 {
6964 clear_waiting_for_input ();
6965 redisplay_preserve_echo_area (15);
6966 if (read_kbd < 0)
6967 set_waiting_for_input (&timeout);
6968 }
6969
6970 if (read_kbd && detect_input_pending ())
6971 {
6972 nfds = 0;
6973 FD_ZERO (&waitchannels);
6974 }
6975 else
6976 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
6977
6978 xerrno = errno;
6979
6980 /* Make C-g and alarm signals set flags again */
6981 clear_waiting_for_input ();
6982
6983 /* If we woke up due to SIGWINCH, actually change size now. */
6984 do_pending_window_change (0);
6985
6986 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
6987 /* We waited the full specified time, so return now. */
6988 break;
6989
6990 if (nfds == -1)
6991 {
6992 /* If the system call was interrupted, then go around the
6993 loop again. */
6994 if (xerrno == EINTR)
6995 FD_ZERO (&waitchannels);
6996 else
6997 error ("select error: %s", emacs_strerror (xerrno));
6998 }
6999
7000 /* Check for keyboard input */
7001
7002 if (read_kbd
7003 && detect_input_pending_run_timers (do_display))
7004 {
7005 swallow_events (do_display);
7006 if (detect_input_pending_run_timers (do_display))
7007 break;
7008 }
7009
7010 /* If there is unread keyboard input, also return. */
7011 if (read_kbd
7012 && requeued_events_pending_p ())
7013 break;
7014
7015 /* If wait_for_cell. check for keyboard input
7016 but don't run any timers.
7017 ??? (It seems wrong to me to check for keyboard
7018 input at all when wait_for_cell, but the code
7019 has been this way since July 1994.
7020 Try changing this after version 19.31.) */
7021 if (! NILP (wait_for_cell)
7022 && detect_input_pending ())
7023 {
7024 swallow_events (do_display);
7025 if (detect_input_pending ())
7026 break;
7027 }
7028
7029 /* Exit now if the cell we're waiting for became non-nil. */
7030 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7031 break;
7032 }
7033
7034 start_polling ();
7035
7036 return 0;
7037 }
7038
7039 #endif /* not subprocesses */
7040
7041 /* The following functions are needed even if async subprocesses are
7042 not supported. Some of them are no-op stubs in that case. */
7043
7044 /* Add DESC to the set of keyboard input descriptors. */
7045
7046 void
7047 add_keyboard_wait_descriptor (int desc)
7048 {
7049 #ifdef subprocesses /* actually means "not MSDOS" */
7050 FD_SET (desc, &input_wait_mask);
7051 FD_SET (desc, &non_process_wait_mask);
7052 if (desc > max_input_desc)
7053 max_input_desc = desc;
7054 #endif
7055 }
7056
7057 /* From now on, do not expect DESC to give keyboard input. */
7058
7059 void
7060 delete_keyboard_wait_descriptor (int desc)
7061 {
7062 #ifdef subprocesses
7063 int fd;
7064 int lim = max_input_desc;
7065
7066 FD_CLR (desc, &input_wait_mask);
7067 FD_CLR (desc, &non_process_wait_mask);
7068
7069 if (desc == max_input_desc)
7070 for (fd = 0; fd < lim; fd++)
7071 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
7072 max_input_desc = fd;
7073 #endif
7074 }
7075
7076 /* Setup coding systems of PROCESS. */
7077
7078 void
7079 setup_process_coding_systems (Lisp_Object process)
7080 {
7081 #ifdef subprocesses
7082 struct Lisp_Process *p = XPROCESS (process);
7083 int inch = p->infd;
7084 int outch = p->outfd;
7085 Lisp_Object coding_system;
7086
7087 if (inch < 0 || outch < 0)
7088 return;
7089
7090 if (!proc_decode_coding_system[inch])
7091 proc_decode_coding_system[inch]
7092 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7093 coding_system = p->decode_coding_system;
7094 if (! NILP (p->filter))
7095 ;
7096 else if (BUFFERP (p->buffer))
7097 {
7098 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
7099 coding_system = raw_text_coding_system (coding_system);
7100 }
7101 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7102
7103 if (!proc_encode_coding_system[outch])
7104 proc_encode_coding_system[outch]
7105 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7106 setup_coding_system (p->encode_coding_system,
7107 proc_encode_coding_system[outch]);
7108 #endif
7109 }
7110
7111 /* Close all descriptors currently in use for communication
7112 with subprocess. This is used in a newly-forked subprocess
7113 to get rid of irrelevant descriptors. */
7114
7115 void
7116 close_process_descs (void)
7117 {
7118 #ifndef DOS_NT
7119 int i;
7120 for (i = 0; i < MAXDESC; i++)
7121 {
7122 Lisp_Object process;
7123 process = chan_process[i];
7124 if (!NILP (process))
7125 {
7126 int in = XPROCESS (process)->infd;
7127 int out = XPROCESS (process)->outfd;
7128 if (in >= 0)
7129 emacs_close (in);
7130 if (out >= 0 && in != out)
7131 emacs_close (out);
7132 }
7133 }
7134 #endif
7135 }
7136
7137 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7138 doc: /* Return the (or a) process associated with BUFFER.
7139 BUFFER may be a buffer or the name of one. */)
7140 (register Lisp_Object buffer)
7141 {
7142 #ifdef subprocesses
7143 register Lisp_Object buf, tail, proc;
7144
7145 if (NILP (buffer)) return Qnil;
7146 buf = Fget_buffer (buffer);
7147 if (NILP (buf)) return Qnil;
7148
7149 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7150 {
7151 proc = Fcdr (XCAR (tail));
7152 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
7153 return proc;
7154 }
7155 #endif /* subprocesses */
7156 return Qnil;
7157 }
7158
7159 DEFUN ("process-inherit-coding-system-flag",
7160 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7161 1, 1, 0,
7162 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7163 If this flag is t, `buffer-file-coding-system' of the buffer
7164 associated with PROCESS will inherit the coding system used to decode
7165 the process output. */)
7166 (register Lisp_Object process)
7167 {
7168 #ifdef subprocesses
7169 CHECK_PROCESS (process);
7170 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7171 #else
7172 /* Ignore the argument and return the value of
7173 inherit-process-coding-system. */
7174 return inherit_process_coding_system ? Qt : Qnil;
7175 #endif
7176 }
7177
7178 /* Kill all processes associated with `buffer'.
7179 If `buffer' is nil, kill all processes */
7180
7181 void
7182 kill_buffer_processes (Lisp_Object buffer)
7183 {
7184 #ifdef subprocesses
7185 Lisp_Object tail, proc;
7186
7187 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7188 {
7189 proc = XCDR (XCAR (tail));
7190 if (PROCESSP (proc)
7191 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
7192 {
7193 if (NETCONN_P (proc) || SERIALCONN_P (proc))
7194 Fdelete_process (proc);
7195 else if (XPROCESS (proc)->infd >= 0)
7196 process_send_signal (proc, SIGHUP, Qnil, 1);
7197 }
7198 }
7199 #else /* subprocesses */
7200 /* Since we have no subprocesses, this does nothing. */
7201 #endif /* subprocesses */
7202 }
7203
7204 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
7205 Swaiting_for_user_input_p, 0, 0, 0,
7206 doc: /* Returns non-nil if Emacs is waiting for input from the user.
7207 This is intended for use by asynchronous process output filters and sentinels. */)
7208 (void)
7209 {
7210 #ifdef subprocesses
7211 return (waiting_for_user_input_p ? Qt : Qnil);
7212 #else
7213 return Qnil;
7214 #endif
7215 }
7216
7217 /* Stop reading input from keyboard sources. */
7218
7219 void
7220 hold_keyboard_input (void)
7221 {
7222 kbd_is_on_hold = 1;
7223 }
7224
7225 /* Resume reading input from keyboard sources. */
7226
7227 void
7228 unhold_keyboard_input (void)
7229 {
7230 kbd_is_on_hold = 0;
7231 }
7232
7233 /* Return non-zero if keyboard input is on hold, zero otherwise. */
7234
7235 int
7236 kbd_on_hold_p (void)
7237 {
7238 return kbd_is_on_hold;
7239 }
7240
7241 \f
7242 /* Enumeration of and access to system processes a-la ps(1). */
7243
7244 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7245 0, 0, 0,
7246 doc: /* Return a list of numerical process IDs of all running processes.
7247 If this functionality is unsupported, return nil.
7248
7249 See `process-attributes' for getting attributes of a process given its ID. */)
7250 (void)
7251 {
7252 return list_system_processes ();
7253 }
7254
7255 DEFUN ("process-attributes", Fprocess_attributes,
7256 Sprocess_attributes, 1, 1, 0,
7257 doc: /* Return attributes of the process given by its PID, a number.
7258
7259 Value is an alist where each element is a cons cell of the form
7260
7261 \(KEY . VALUE)
7262
7263 If this functionality is unsupported, the value is nil.
7264
7265 See `list-system-processes' for getting a list of all process IDs.
7266
7267 The KEYs of the attributes that this function may return are listed
7268 below, together with the type of the associated VALUE (in parentheses).
7269 Not all platforms support all of these attributes; unsupported
7270 attributes will not appear in the returned alist.
7271 Unless explicitly indicated otherwise, numbers can have either
7272 integer or floating point values.
7273
7274 euid -- Effective user User ID of the process (number)
7275 user -- User name corresponding to euid (string)
7276 egid -- Effective user Group ID of the process (number)
7277 group -- Group name corresponding to egid (string)
7278 comm -- Command name (executable name only) (string)
7279 state -- Process state code, such as "S", "R", or "T" (string)
7280 ppid -- Parent process ID (number)
7281 pgrp -- Process group ID (number)
7282 sess -- Session ID, i.e. process ID of session leader (number)
7283 ttname -- Controlling tty name (string)
7284 tpgid -- ID of foreground process group on the process's tty (number)
7285 minflt -- number of minor page faults (number)
7286 majflt -- number of major page faults (number)
7287 cminflt -- cumulative number of minor page faults (number)
7288 cmajflt -- cumulative number of major page faults (number)
7289 utime -- user time used by the process, in (current-time) format,
7290 which is a list of integers (HIGH LOW USEC PSEC)
7291 stime -- system time used by the process (current-time)
7292 time -- sum of utime and stime (current-time)
7293 cutime -- user time used by the process and its children (current-time)
7294 cstime -- system time used by the process and its children (current-time)
7295 ctime -- sum of cutime and cstime (current-time)
7296 pri -- priority of the process (number)
7297 nice -- nice value of the process (number)
7298 thcount -- process thread count (number)
7299 start -- time the process started (current-time)
7300 vsize -- virtual memory size of the process in KB's (number)
7301 rss -- resident set size of the process in KB's (number)
7302 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7303 pcpu -- percents of CPU time used by the process (floating-point number)
7304 pmem -- percents of total physical memory used by process's resident set
7305 (floating-point number)
7306 args -- command line which invoked the process (string). */)
7307 ( Lisp_Object pid)
7308 {
7309 return system_process_attributes (pid);
7310 }
7311
7312 \f
7313 void
7314 init_process (void)
7315 {
7316 #ifdef subprocesses
7317 register int i;
7318
7319 inhibit_sentinels = 0;
7320
7321 #ifdef SIGCHLD
7322 #ifndef CANNOT_DUMP
7323 if (! noninteractive || initialized)
7324 #endif
7325 signal (SIGCHLD, sigchld_handler);
7326 #endif
7327
7328 FD_ZERO (&input_wait_mask);
7329 FD_ZERO (&non_keyboard_wait_mask);
7330 FD_ZERO (&non_process_wait_mask);
7331 FD_ZERO (&write_mask);
7332 max_process_desc = 0;
7333 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7334
7335 #ifdef NON_BLOCKING_CONNECT
7336 FD_ZERO (&connect_wait_mask);
7337 num_pending_connects = 0;
7338 #endif
7339
7340 #ifdef ADAPTIVE_READ_BUFFERING
7341 process_output_delay_count = 0;
7342 process_output_skip = 0;
7343 #endif
7344
7345 /* Don't do this, it caused infinite select loops. The display
7346 method should call add_keyboard_wait_descriptor on stdin if it
7347 needs that. */
7348 #if 0
7349 FD_SET (0, &input_wait_mask);
7350 #endif
7351
7352 Vprocess_alist = Qnil;
7353 #ifdef SIGCHLD
7354 deleted_pid_list = Qnil;
7355 #endif
7356 for (i = 0; i < MAXDESC; i++)
7357 {
7358 chan_process[i] = Qnil;
7359 proc_buffered_char[i] = -1;
7360 }
7361 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7362 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7363 #ifdef DATAGRAM_SOCKETS
7364 memset (datagram_address, 0, sizeof datagram_address);
7365 #endif
7366
7367 {
7368 Lisp_Object subfeatures = Qnil;
7369 const struct socket_options *sopt;
7370
7371 #define ADD_SUBFEATURE(key, val) \
7372 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7373
7374 #ifdef NON_BLOCKING_CONNECT
7375 ADD_SUBFEATURE (QCnowait, Qt);
7376 #endif
7377 #ifdef DATAGRAM_SOCKETS
7378 ADD_SUBFEATURE (QCtype, Qdatagram);
7379 #endif
7380 #ifdef HAVE_SEQPACKET
7381 ADD_SUBFEATURE (QCtype, Qseqpacket);
7382 #endif
7383 #ifdef HAVE_LOCAL_SOCKETS
7384 ADD_SUBFEATURE (QCfamily, Qlocal);
7385 #endif
7386 ADD_SUBFEATURE (QCfamily, Qipv4);
7387 #ifdef AF_INET6
7388 ADD_SUBFEATURE (QCfamily, Qipv6);
7389 #endif
7390 #ifdef HAVE_GETSOCKNAME
7391 ADD_SUBFEATURE (QCservice, Qt);
7392 #endif
7393 #if defined (O_NONBLOCK) || defined (O_NDELAY)
7394 ADD_SUBFEATURE (QCserver, Qt);
7395 #endif
7396
7397 for (sopt = socket_options; sopt->name; sopt++)
7398 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7399
7400 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7401 }
7402
7403 #if defined (DARWIN_OS)
7404 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7405 processes. As such, we only change the default value. */
7406 if (initialized)
7407 {
7408 char const *release = (STRINGP (Voperating_system_release)
7409 ? SSDATA (Voperating_system_release)
7410 : 0);
7411 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7412 && release[1] == '.')) {
7413 Vprocess_connection_type = Qnil;
7414 }
7415 }
7416 #endif
7417 #endif /* subprocesses */
7418 kbd_is_on_hold = 0;
7419 }
7420
7421 void
7422 syms_of_process (void)
7423 {
7424 #ifdef subprocesses
7425
7426 DEFSYM (Qprocessp, "processp");
7427 DEFSYM (Qrun, "run");
7428 DEFSYM (Qstop, "stop");
7429 DEFSYM (Qsignal, "signal");
7430
7431 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7432 here again.
7433
7434 Qexit = intern_c_string ("exit");
7435 staticpro (&Qexit); */
7436
7437 DEFSYM (Qopen, "open");
7438 DEFSYM (Qclosed, "closed");
7439 DEFSYM (Qconnect, "connect");
7440 DEFSYM (Qfailed, "failed");
7441 DEFSYM (Qlisten, "listen");
7442 DEFSYM (Qlocal, "local");
7443 DEFSYM (Qipv4, "ipv4");
7444 #ifdef AF_INET6
7445 DEFSYM (Qipv6, "ipv6");
7446 #endif
7447 DEFSYM (Qdatagram, "datagram");
7448 DEFSYM (Qseqpacket, "seqpacket");
7449
7450 DEFSYM (QCport, ":port");
7451 DEFSYM (QCspeed, ":speed");
7452 DEFSYM (QCprocess, ":process");
7453
7454 DEFSYM (QCbytesize, ":bytesize");
7455 DEFSYM (QCstopbits, ":stopbits");
7456 DEFSYM (QCparity, ":parity");
7457 DEFSYM (Qodd, "odd");
7458 DEFSYM (Qeven, "even");
7459 DEFSYM (QCflowcontrol, ":flowcontrol");
7460 DEFSYM (Qhw, "hw");
7461 DEFSYM (Qsw, "sw");
7462 DEFSYM (QCsummary, ":summary");
7463
7464 DEFSYM (Qreal, "real");
7465 DEFSYM (Qnetwork, "network");
7466 DEFSYM (Qserial, "serial");
7467 DEFSYM (QCbuffer, ":buffer");
7468 DEFSYM (QChost, ":host");
7469 DEFSYM (QCservice, ":service");
7470 DEFSYM (QClocal, ":local");
7471 DEFSYM (QCremote, ":remote");
7472 DEFSYM (QCcoding, ":coding");
7473 DEFSYM (QCserver, ":server");
7474 DEFSYM (QCnowait, ":nowait");
7475 DEFSYM (QCsentinel, ":sentinel");
7476 DEFSYM (QClog, ":log");
7477 DEFSYM (QCnoquery, ":noquery");
7478 DEFSYM (QCstop, ":stop");
7479 DEFSYM (QCoptions, ":options");
7480 DEFSYM (QCplist, ":plist");
7481
7482 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7483
7484 staticpro (&Vprocess_alist);
7485 #ifdef SIGCHLD
7486 staticpro (&deleted_pid_list);
7487 #endif
7488
7489 #endif /* subprocesses */
7490
7491 DEFSYM (QCname, ":name");
7492 DEFSYM (QCtype, ":type");
7493
7494 DEFSYM (Qeuid, "euid");
7495 DEFSYM (Qegid, "egid");
7496 DEFSYM (Quser, "user");
7497 DEFSYM (Qgroup, "group");
7498 DEFSYM (Qcomm, "comm");
7499 DEFSYM (Qstate, "state");
7500 DEFSYM (Qppid, "ppid");
7501 DEFSYM (Qpgrp, "pgrp");
7502 DEFSYM (Qsess, "sess");
7503 DEFSYM (Qttname, "ttname");
7504 DEFSYM (Qtpgid, "tpgid");
7505 DEFSYM (Qminflt, "minflt");
7506 DEFSYM (Qmajflt, "majflt");
7507 DEFSYM (Qcminflt, "cminflt");
7508 DEFSYM (Qcmajflt, "cmajflt");
7509 DEFSYM (Qutime, "utime");
7510 DEFSYM (Qstime, "stime");
7511 DEFSYM (Qtime, "time");
7512 DEFSYM (Qcutime, "cutime");
7513 DEFSYM (Qcstime, "cstime");
7514 DEFSYM (Qctime, "ctime");
7515 DEFSYM (Qpri, "pri");
7516 DEFSYM (Qnice, "nice");
7517 DEFSYM (Qthcount, "thcount");
7518 DEFSYM (Qstart, "start");
7519 DEFSYM (Qvsize, "vsize");
7520 DEFSYM (Qrss, "rss");
7521 DEFSYM (Qetime, "etime");
7522 DEFSYM (Qpcpu, "pcpu");
7523 DEFSYM (Qpmem, "pmem");
7524 DEFSYM (Qargs, "args");
7525
7526 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7527 doc: /* Non-nil means delete processes immediately when they exit.
7528 A value of nil means don't delete them until `list-processes' is run. */);
7529
7530 delete_exited_processes = 1;
7531
7532 #ifdef subprocesses
7533 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7534 doc: /* Control type of device used to communicate with subprocesses.
7535 Values are nil to use a pipe, or t or `pty' to use a pty.
7536 The value has no effect if the system has no ptys or if all ptys are busy:
7537 then a pipe is used in any case.
7538 The value takes effect when `start-process' is called. */);
7539 Vprocess_connection_type = Qt;
7540
7541 #ifdef ADAPTIVE_READ_BUFFERING
7542 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7543 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7544 On some systems, when Emacs reads the output from a subprocess, the output data
7545 is read in very small blocks, potentially resulting in very poor performance.
7546 This behavior can be remedied to some extent by setting this variable to a
7547 non-nil value, as it will automatically delay reading from such processes, to
7548 allow them to produce more output before Emacs tries to read it.
7549 If the value is t, the delay is reset after each write to the process; any other
7550 non-nil value means that the delay is not reset on write.
7551 The variable takes effect when `start-process' is called. */);
7552 Vprocess_adaptive_read_buffering = Qt;
7553 #endif
7554
7555 defsubr (&Sprocessp);
7556 defsubr (&Sget_process);
7557 defsubr (&Sdelete_process);
7558 defsubr (&Sprocess_status);
7559 defsubr (&Sprocess_exit_status);
7560 defsubr (&Sprocess_id);
7561 defsubr (&Sprocess_name);
7562 defsubr (&Sprocess_tty_name);
7563 defsubr (&Sprocess_command);
7564 defsubr (&Sset_process_buffer);
7565 defsubr (&Sprocess_buffer);
7566 defsubr (&Sprocess_mark);
7567 defsubr (&Sset_process_filter);
7568 defsubr (&Sprocess_filter);
7569 defsubr (&Sset_process_sentinel);
7570 defsubr (&Sprocess_sentinel);
7571 defsubr (&Sset_process_window_size);
7572 defsubr (&Sset_process_inherit_coding_system_flag);
7573 defsubr (&Sset_process_query_on_exit_flag);
7574 defsubr (&Sprocess_query_on_exit_flag);
7575 defsubr (&Sprocess_contact);
7576 defsubr (&Sprocess_plist);
7577 defsubr (&Sset_process_plist);
7578 defsubr (&Sprocess_list);
7579 defsubr (&Sstart_process);
7580 defsubr (&Sserial_process_configure);
7581 defsubr (&Smake_serial_process);
7582 defsubr (&Sset_network_process_option);
7583 defsubr (&Smake_network_process);
7584 defsubr (&Sformat_network_address);
7585 #if defined (HAVE_NET_IF_H)
7586 #ifdef SIOCGIFCONF
7587 defsubr (&Snetwork_interface_list);
7588 #endif
7589 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
7590 defsubr (&Snetwork_interface_info);
7591 #endif
7592 #endif /* defined (HAVE_NET_IF_H) */
7593 #ifdef DATAGRAM_SOCKETS
7594 defsubr (&Sprocess_datagram_address);
7595 defsubr (&Sset_process_datagram_address);
7596 #endif
7597 defsubr (&Saccept_process_output);
7598 defsubr (&Sprocess_send_region);
7599 defsubr (&Sprocess_send_string);
7600 defsubr (&Sinterrupt_process);
7601 defsubr (&Skill_process);
7602 defsubr (&Squit_process);
7603 defsubr (&Sstop_process);
7604 defsubr (&Scontinue_process);
7605 defsubr (&Sprocess_running_child_p);
7606 defsubr (&Sprocess_send_eof);
7607 defsubr (&Ssignal_process);
7608 defsubr (&Swaiting_for_user_input_p);
7609 defsubr (&Sprocess_type);
7610 defsubr (&Sset_process_coding_system);
7611 defsubr (&Sprocess_coding_system);
7612 defsubr (&Sset_process_filter_multibyte);
7613 defsubr (&Sprocess_filter_multibyte_p);
7614
7615 #endif /* subprocesses */
7616
7617 defsubr (&Sget_buffer_process);
7618 defsubr (&Sprocess_inherit_coding_system_flag);
7619 defsubr (&Slist_system_processes);
7620 defsubr (&Sprocess_attributes);
7621 }