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