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