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